﻿Option Explicit On

Imports System.Text
Imports System.IO
Imports Microsoft.Office.Interop
Imports System.Data
Imports System.ComponentModel
Imports CRM.BusinessLayer
Imports CRM.BusinessLayer.CommonDataFunctions
Imports System.Reflection
Imports Microsoft.Office.Interop.Word
Imports iTextSharp.text.pdf


Partial Public Class frmCRMMainDisplay
    Private _StopDuplicateLoad As Boolean = False
    Public Event CloseDynamicTab(ByVal userControlName As String)
    Public Event ShowDynamicTab(ByVal userControlName As String)
    Public Shared blnAmendDataBeforeEmail As Boolean
    Public Shared blnCancelEmail As Boolean
    Public _blnCancelPaymentPlan As Boolean
    Public Shared blnCancelPaymentPlan As Boolean
    Private checkLoad As Boolean
    Public Shared loadTabEvent As Boolean = False
    Public Shared loadTabCases As Boolean = False
    Public Shared loadTabPeople As Boolean = False
    Public Shared loadTabDocs As Boolean = False
    Public Shared loadTabAccounts As Boolean = False
    Public Shared loadTabCompany As Boolean = False
    Public Shared rowselectionchanged As Boolean = False
    Public Shared contentOfButtonPressed As String = String.Empty


    Private Enum EventView
        Company = 1
        Person = 2
        CaseId = 3
        Consultant = 4
        All = 5
        Combined = 6
    End Enum

    Private Enum ViewByStatus
        AllOpen = 1
        PreSale = 2
        Initiated = 3
        Closed = 4
        AllCases = 5
    End Enum

    Private Enum CaseTypes
        Candidate = 1
        Company = 2
    End Enum

    Private Enum ScreenGrids
        CaseSummary = 1
        InvoiceSummary = 2
    End Enum

    Public Enum PageTabs
        NotSet = 0
        Company = 1
        Person = 2
        Cases = 3
        Events = 4
        Accounts = 5
    End Enum

    Private _ActiveTab As PageTabs
    Private m_strCurrencyChar As String
    'Private m_bCloseMe As Boolean = False

    Public Property ActiveTab() As PageTabs
        Get
            Return _ActiveTab
        End Get
        Set(ByVal value As PageTabs)
            _ActiveTab = value
        End Set
    End Property
    Public ReadOnly Property ActivePersonName() As String
        Get
            'This is person that is being edited / viewed via the Person panel, not necessarily the active candidate in the case
            Dim tabItemFlag As Boolean = False
            For Each item As TabItem In TabControl1.Items
                If item.Name = "tabCompany" Then
                    tabItemFlag = True
                    Exit For
                Else
                    tabItemFlag = False
                End If
            Next
            If tabItemFlag = False Then
                Return GlobalCRM.CurrentCandidateName
            Else
                If Me.lvwPeopleList.SelectedItems.Count > 0 Then
                    Return Me.lvwPeopleList.SelectedItem.row.itemarray(1).ToString
                Else
                    Return String.Empty
                End If
            End If

        End Get

    End Property
    Public ReadOnly Property ActivePersonId() As Long
        Get
            'This is person that is being edited / viewed via the Person panel, not necessarily the active candidate in the case
            Dim tabItemFlag As Boolean = False
            For Each item As TabItem In TabControl1.Items
                If item.Name = "tabCompany" Then
                    If item.Visibility = System.Windows.Visibility.Visible Then
                        tabItemFlag = True
                        Exit For

                    End If
                Else
                    tabItemFlag = False
                End If
            Next
            If tabItemFlag = False Then
                Return GlobalCRM.CurrentCandidateID
            Else
                If Me.lvwPeopleList.SelectedItems.Count > 0 Then
                    Return Me.lvwPeopleList.SelectedItem.row.itemarray(0).ToString
                Else
                    Return 0
                End If
            End If

        End Get

    End Property


    Public Sub frmMainDisplay_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        'Dim MDI As New frmCRMMDI
        If checkLoad = True Then
            Exit Sub
        End If
        Try
            GeneralTasks.ChangeTheme(Me)
            GeneralTasks.EnumerateandFill(Me.LogicalChildren)

            If LoadMainPage() = False Then
                CommonFuncs.DisplayMessage("Load Failed. Please contact IT", CommonDialog.CustomDialogIcons.Information, "Failed")
            End If
            checkLoad = True
        Catch exc As Exception
            CommonFuncs.ErrorHandler(exc, "frmMainDisplay.Load")
        Finally
            'MDI = Nothing
            Me.txtGoto.Focus()
        End Try
    End Sub
    Public Function LoadMainPage() As Boolean
        Dim myData As System.Data.DataTable = Nothing
        Try

            TabControl1.SelectedItem = GlobalCRM.TabSelection
            Me.Cursor = Cursors.Arrow

            Me.ClearScreen()
            rowselectionchanged = False
            'Me.grdCases.SelectedItems.Clear()
            Me.cmbEmailTo.SelectedIndex = 1
            If GlobalCRM.CurrentCompanyID = 0 Then
                Try
                    'Me.TabControl1.Items.Remove(Me.tabCompany)
                    'Me.TabControl1.Items(0).visibility = hidden
                    tabCompany.Visibility = System.Windows.Visibility.Hidden
                Catch ex As Exception
                    Try
                        'Me.TabControl1.Items.Remove(Me.tabCompany)
                    Catch ex1 As Exception

                    End Try
                End Try
            Else
                tabCompany.Visibility = System.Windows.Visibility.Visible
                FillCompanyDetails()
            End If

            If GlobalCRM.CurrentCompanyID = 0 Then
                Me.lblCandidateName.Text = GlobalCRM.CurrentCandidateName
                Me.lblCandidateID.Text = GlobalCRM.CurrentCandidateID
            Else
                If GlobalCRM.CurrentCompanyID > 0 Then
                    GlobalCRM.CurrentCompanyName = GetCompanyName(GlobalCRM.CurrentCompanyID)
                End If
                If GlobalCRM.CurrentCompanyName Is Nothing Then
                    GlobalCRM.CurrentCompanyName = GetCompanyName(GlobalCRM.CurrentCompanyID)
                ElseIf GlobalCRM.CurrentCompanyName = String.Empty Or GlobalCRM.CurrentCompanyName = "0" Then
                    GlobalCRM.CurrentCompanyName = GetCompanyName(GlobalCRM.CurrentCompanyID)
                End If
                Me.lblCandidateName.Text = GlobalCRM.CurrentCompanyName
                Me.lblCandidateID.Text = GlobalCRM.CurrentCompanyID
            End If
            Me.lblCandidateName3.Text = GlobalCRM.CurrentCandidateName
            Me.lblCandidateId3.Text = GlobalCRM.CurrentCandidateID

            If GlobalCRM.CurrentCompanyID = 0 Then
                Me.lblCon1.Visibility = System.Windows.Visibility.Hidden
                Me.lblContactId.Visibility = System.Windows.Visibility.Hidden
                Me.lblContactName.Visibility = System.Windows.Visibility.Hidden


                Me.lblPrivateMessage.Visibility = System.Windows.Visibility.Visible
                btnAddtoCompany.Visibility = System.Windows.Visibility.Visible

            Else

                If TabControl1.Items.Count = 5 Then
                Else
                    Dim tabitem As TabItem = Me.TabControl1.Items(0)
                    tabitem.Visibility = System.Windows.Visibility.Visible
                End If
                Me.lblPrivateMessage.Visibility = System.Windows.Visibility.Hidden
                btnAddtoCompany.Visibility = System.Windows.Visibility.Hidden
                'RemoveHandler drpRoles.SelectionChanged, AddressOf drpRoles_SelectionChanged

            End If

            If GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCompany Then
                Me.TabControl1.SelectedItem = Me.tabCompany
            ElseIf GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.ePerson Then
                Me.TabControl1.SelectedItem = Me.tabPeople
            ElseIf GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCase Then
                Me.TabControl1.SelectedItem = Me.tabCase
            ElseIf GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eEvent Then
                Me.TabControl1.SelectedItem = Me.tabEvent
            ElseIf GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eInvoice Then
                Me.TabControl1.SelectedItem = Me.tabAccount
            Else
                ' if nothing specified show people tab
                Me.TabControl1.SelectedItem = Me.tabPeople
            End If


            Me.AddHandlers()

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Sub FillCompanyDetails()
        Dim myCompany As Company.CompanyInfo = Company.GetCompany(GlobalCRM.CurrentCompanyID)
        With myCompany
            lblCompanyName.Text = myCompany.CompanyName
        End With
    End Sub


    Public Shared Sub SelectListviewRow(ByVal AnyList As System.Windows.Controls.ListView, ByVal ListId As Long)

        Dim li As DataRowView

        AnyList.SelectedItems.Clear()
        For i = 0 To AnyList.Items.Count - 1
            li = AnyList.Items(i)
            If li.Item(0).ToString = ListId Then
                'AnyList.Items(i).selected = True
                AnyList.SelectedItem = AnyList.Items(i)
                Exit For
            End If
        Next
    End Sub
    Private Function GblFunc_Advance_CaseStage(ByVal CaseID As Long, ByVal AdvanceType As Integer) As Boolean
        Dim frmPaymentPlan As frmPaymentPlan
        Dim tsk As New TasksEvents
        Dim cmn As New CommonFuncs
        Dim myData As System.Data.DataTable
        Dim SQL As New StringBuilder
        Dim myCaseInfo As Cases.CaseInfo
        Dim AccountType As Integer
        Dim ProductType As Integer
        Dim DiagramId As Integer
        Dim ClientType As Integer
        Dim StageLinkTo As Integer
        Dim StageLinkDescription As String
        Dim StageLinkKeyDate As Integer
        Dim myPerson As People.PersonInfo
        Dim VisaExpiry As Integer
        Dim Ret As Integer
        Dim paidamt As Double
        Dim FinanceCheck As Boolean = True
        Dim AddSecondCase As Integer
        Dim CurSubOSAdmin As Decimal
        Dim myProduct As Products.ProductInfo
        Dim Reason As String = String.Empty
        Dim NoExpiry As Integer
        Dim Msg As StringBuilder
        Dim ExpiryDate As String = String.Empty
        Dim CurrentStage As String
        Dim ActiveStatus As Boolean
        ' Dim AutoGroups() As Long
        'Dim AutoLinks() As Long
        'Dim i As Integer
        Dim SalesConId As Integer
        Dim strCurrencyChar As String
        'blnCancelEmail = False

        Try
            myCaseInfo = Cases.GetCaseInfo(CaseID)
            If (myCaseInfo.SalesConid = 0) Then
                MsgBox("Cannot advance a stage without any consultant accociated, Please add a sales consultant in case tab and try again", MsgBoxStyle.YesNo, "No Sales Consultant")
                Exit Function
            End If
            myPerson = People.GetPerson(myCaseInfo.CandidateId)
            If myPerson.PersonId = 0 And myCaseInfo.CompanyId = 0 Then
                MsgBox("Cannot advance a stage without any person accociated, Please add a person in People tab and try again", MsgBoxStyle.YesNo, "No Person")
                Exit Function
            ElseIf myPerson.PersonId = 0 And myCaseInfo.CompanyId > 0 Then
                If MsgBox("The case has no candidate but a company, do you wish to continue?", MsgBoxStyle.YesNo + MsgBoxStyle.Question) = MsgBoxResult.No Then
                    Exit Function
                End If
            End If
            strCurrencyChar = CommonDataFunctions.GetCurrencyCodeCharacter(CaseID)

            'This may change, so keep copy
            ActiveStatus = myCaseInfo.OnHold

            If myCaseInfo.CompanyId > 0 Then
                AccountType = Company.GetAccountType(myCaseInfo.CompanyId)
                If AccountType = 0 Then
                    AccountType = 1
                End If
                ClientType = 2
            Else
                AccountType = 1
                ClientType = 1
            End If

            'Find the case stage diagram from the product or product type
            If myCaseInfo.Productid = 0 Then
                DiagramId = 2
                ProductType = 0
            Else
                DiagramId = CommonDataFunctions.GblFunc_Get_Dataset(CaseID, 1)
                ProductType = Products.GetProductType(myCaseInfo.Productid)
            End If

            If DiagramId = 0 Then
                DiagramId = 2
            End If

            'we have a diagram, so now look up what the next stage should be using the current stage, customer type, diagram and advance type (which should be a unique combination).
            SQL = New StringBuilder

            With SQL
                .Append("SELECT StageLink_toid, StageLink_Desc, stageLink_keydate ")
                .Append(" FROM L_StageLinks ")
                .Append(" WHERE StageLink_FromId = " & myCaseInfo.CaseStatusId & " ")
                .Append(" AND StageLink_position = " & AdvanceType)
                .Append(" AND StageLink_DiagramID = " & DiagramId)
                .Append(" AND StageLink_customertype in (0," & ClientType & ")")
            End With

            myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

            If myData.Rows.Count = 0 Then
                CommonFuncs.DisplayMessage("Error state stage link not found", CommonDialog.CustomDialogIcons.Information, "Link")
                Exit Function
            End If

            If myData.Rows.Count > 1 Then
                CommonFuncs.DisplayMessage("Error state. More than one stage link returned", CommonDialog.CustomDialogIcons.Information, "Link")
                Exit Function
            End If

            StageLinkTo = myData.Rows(0).Item("stagelink_toid")
            StageLinkDescription = myData.Rows(0).Item("stagelink_desc")
            StageLinkKeyDate = myData.Rows(0).Item("Stagelink_keydate") 'can be turned off

            myData.Dispose()
            If StageLinkTo = 100 Then
                If CRM.BusinessLayer.Documents.GetDocCount(GlobalCRM.CurrentCaseID) > 0 Then
                Else
                    'If CommonDataFunctions.GetSQLScalar("Select DefDocReq_ID from D_DefDocReqs where DefDocReq_ProductID = " & myCaseInfo.Productid) = 0 Then
                    '    CommonFuncs.DisplayMessage("No default document requirements found for product " & Products.GetProductName(myCaseInfo.Productid) & ".You would not be able to initiate a case unless the document list is populated.Please speak to your manager", CommonDialog.CustomDialogIcons.Information, "Document")
                    '    Exit Function
                    'Else 
                    Dim FirstCase As Integer
                    SQL = New StringBuilder

                    With SQL
                        .Append("Select count(*) from D_Case ")
                        .Append(" Where Case_ID < " & GlobalCRM.CurrentCaseID)
                        .Append(" And Case_StatusID Between 100 and 1020")

                        If GlobalCRM.CurrentCompanyID = 0 Then
                            .Append(" AND case_CandidateId = " & GlobalCRM.CurrentCandidateID)
                        Else
                            .Append(" AND case_CompanyId = " & GlobalCRM.CurrentCompanyID)
                        End If

                    End With



                    If CommonDataFunctions.GetSQLScalar(SQL.ToString) = 0 Then
                        FirstCase = 1
                    Else
                        FirstCase = 0
                    End If
                    'If Documents.CreateDocumentRequirements(GlobalCRM.CurrentCaseID, myCaseInfo.Productid, myCaseInfo.CompanyId, "Default doc reqs loaded onto case", GlobalCRM.CurrentConID, FirstCase) = True Then

                    'Else
                    '    CommonFuncs.DisplayMessage("There was an error uploading the document in the system. Please try again.", CommonDialog.CustomDialogIcons.Information, "Documents")
                    '    Exit Function
                    'End If
                    'End If
                End If
            End If
            If StageLinkTo >= 100 And StageLinkTo < 1000 Then
                'Reverting back the change- requested by Monica to advance through the cases even if payment is not taken.
                paidamt = Accounts.CasePaidAmt(myCaseInfo.CaseId)
                If paidamt <= 0 Then
                    If myCaseInfo.CompanyId = 0 Then
                        CommonFuncs.DisplayMessage("No Payment made for this case. Hence could not advance through to next stage.", CommonDialog.CustomDialogIcons.Information, "No Payment taken")
                        Exit Function
                    End If
                End If
            End If
            'Now we know what we're doing, time for checks and validation

            'Check if making a sale (case initiated) and do checks if so

            If myCaseInfo.CaseStatusId < 100 And StageLinkTo > 99 And StageLinkTo < 1000 Then
                'Going from pre-sale to initiated, do checks

                'No need to check product as there is no path to initiated without one.

                'Check Candidate details.
                'Is there a candidate?
                If myCaseInfo.CandidateId = 0 And myCaseInfo.CompanyId = 0 Then
                    CommonFuncs.DisplayMessage("Cannot initiate a case without a candidate", CommonDialog.CustomDialogIcons.Information, "Case")
                    Exit Function
                End If

                'Validate the candidates nat, res and UKVisa
                ' myPerson = People.GetPerson(myCaseInfo.CandidateId)

                If myPerson.PersonId > 0 Then
                    If IsNothing(myPerson) Then
                        'Candidate not found
                        CommonFuncs.DisplayMessage("Could not find candidate details, unable to initiate case. Please check and try again", CommonDialog.CustomDialogIcons.Information, "Candidate Detail")
                        Exit Function
                    End If

                    If CommonFuncs.IsDateValid(myPerson.UKVisaExpiry) Then
                        VisaExpiry = 1
                    End If

                    Ret = CommonDataFunctions.GblFunc_Validate_NatResVisa(myPerson.NationalityId, myPerson.ResidenceId, myPerson.UKVisaId, VisaExpiry, 0)

                    Select Case Ret

                        Case 0
                            'All ok, proceed

                        Case 1
                            CommonFuncs.DisplayMessage("Candidate nationality details invalid, cannot initiate case. Please check and try again", CommonDialog.CustomDialogIcons.Information, "Invalid")
                            Exit Function

                        Case 2
                            CommonFuncs.DisplayMessage("Candidate residence details invalid, cannot initiate case. Please check and try again", CommonDialog.CustomDialogIcons.Information, "Invalid")
                            Exit Function

                        Case 3
                            CommonFuncs.DisplayMessage("Candidate UK visa details invalid, cannot initiate case. Please check and try again", CommonDialog.CustomDialogIcons.Information, "Invalid")
                            Exit Function

                        Case 4
                            CommonFuncs.DisplayMessage("Candidate's current UK visa expiry date not provided for non-indefinate visa type. Cannot initiate case. Please check and try again", CommonDialog.CustomDialogIcons.Information, "Case Initiation")
                            Exit Function

                        Case 5
                            CommonFuncs.DisplayMessage("Candidate's Nationality, Residence or UK Visa is set to 'Unknown'. Cannot initiate case. Please check and try again", CommonDialog.CustomDialogIcons.Information, "Case Initiation")
                            Exit Function

                        Case 10
                            CommonFuncs.DisplayMessage("Error while trying to validate candidate, unable to initiate case. Please check candidates status and try again. If the problem persists speak to the IT dept", CommonDialog.CustomDialogIcons.Information, "Case Initiation")
                            Exit Function
                    End Select
                End If


                'can add admin tool for accounts to put a STOP on company
                'If company, check for stop status
                If myCaseInfo.CompanyId <> 0 Then
                    If Company.GetStopStatus(myCaseInfo.CompanyId) = 1 Then
                        CommonFuncs.DisplayMessage("This company is on stop, cannot initiate a new case", CommonDialog.CustomDialogIcons.Information, "Company on Stop")
                        Exit Function
                    End If

                End If
                'MJG 7/Jul/07
                'End If

                'Check that something has been quoted.

                'dont check if this is a secondary app

                'Check if this is an FLR or EC case with a second case open (e.g this is the EC or FLR component of a WP or HSMP)
                If myCaseInfo.Productid = 75 Or myCaseInfo.Productid = 20 Or myCaseInfo.Productid = 209 Then
                    SQL = New StringBuilder
                    With SQL
                        .Append("Select case_Id from D_Case ")
                        .Append(" Where Case_CandidateID =" & myCaseInfo.CandidateId)
                        .Append(" And Case_StatusId Between 100 and 999 ")
                        .Append(" And Case_ID <> " & myCaseInfo.CaseId)
                    End With

                    myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                    If myData.Rows.Count > 0 Then
                        FinanceCheck = False
                    End If

                    myData.Dispose()

                    If FinanceCheck Then

                        Dim NetQuote As Double

                        NetQuote = CommonDataFunctions.GetSQLScalar("Select netquote from V_Case where Case_Id = " & myCaseInfo.CaseId)

                        If NetQuote = 0 Then
                            CommonFuncs.DisplayMessage("No charges have been quoted for this case, you must add charges before it can be sold.", CommonDialog.CustomDialogIcons.Information, "No Charges")
                            Exit Function
                        End If
                    End If

                    'check if initiating a case which may need a secondary application.

                    If ProductType = 1 Then
                        'Skilled Imm product so may need secondary case for FLR/EC

                        'Check if there is an existing open secondary case of the correct type.
                        '75 = UK FLR
                        '20 = UK EC
                        '209 = UK FLR (FT)

                        SQL = New StringBuilder

                        With SQL
                            .Append("Select Case_ID from D_Case where Case_CandidateID = " & myCaseInfo.CandidateId)
                            .Append(" And Case_StatusID < 1000")
                            .Append(" And Case_ProductID In (75,20,209)")
                        End With

                        myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                        If myData.Rows.Count = 0 Then
                            'No case already, ask if they want to add one.


                            'Select Case xMsgBox("Do you want to add a secondary case to this clent?", "Add Secondary Case", FlagType.mbQuestion, DefaultButton.mbDefaultButton3, , , "Add UK FLR", "Add UK EC", "Dont Add")

                            '    Case 1
                            '        If MsgBox("Do you want to Fast Track the UK FLR?", vbYesNo, "Fast Track") <> MsgBoxResult.Yes Then
                            '            AddSecondCase = 75
                            '        Else
                            '            AddSecondCase = 209
                            '        End If

                            '    Case 2
                            '        AddSecondCase = 20

                            'End Select
                        End If
                        myData.Dispose()
                    End If
                End If

                'MG 7/7/7 
            End If

            'End of sale made checks
            ''
            ''
            'Check if submitting to authority. 160 = WPUK, 151 = HO, 152 = DIMIA, 154 = NIS
            'WPUK used to be 150 keep an eye out


            If (StageLinkTo > 149 And StageLinkTo < 155) Or StageLinkTo = 160 Then
                FinanceCheck = True

                'If not SLA then check that all charges are invoiced and the OS is zero

                'Check if this is an FLR or EC case with a second case open (e.g this is the EC or FLR component of a WP or HSMP)
                If myCaseInfo.Productid = 75 Or myCaseInfo.Productid = 20 Or myCaseInfo.Productid = 209 Then
                    SQL = New StringBuilder
                    With SQL
                        .Append("Select Case_PrimaryCaseID  from D_Case ")
                        .Append(" Where Case_CandidateID =" & myCaseInfo.CandidateId)
                        .Append(" And Case_StatusId Between 100 and 999 ") ' lets 2nd case through
                        .Append(" And case_Id = " & CaseID & " AND Case_PrimaryCaseID > 0")
                    End With
                    If CommonDataFunctions.GetSQLScalar(SQL.ToString) > 0 Then
                        FinanceCheck = False
                    End If
                End If

                If myCaseInfo.CompanyId > 0 Then
                    If Company.GetAccountType(myCaseInfo.CompanyId) = 2 Then
                        'SLA
                        FinanceCheck = False
                    End If
                End If

                If FinanceCheck Then

                    myData = CommonDataFunctions.GetSQLDatatable("Select netnotinv,balance,netinv from V_Case where Case_Id = " & CaseID)

                    If myData.Rows.Count = 0 Then
                        CommonFuncs.DisplayMessage("Unable to validate finance when submitting", CommonDialog.CustomDialogIcons.Information, "Finance Validation")
                        Exit Function
                    End If

                    If myData.Rows(0).Item("netnotinv") <> 0 Then
                        CommonFuncs.DisplayMessage(strCurrencyChar & myData.Rows(0).Item("netnotinv") & " worth of charges are uninvoiced on this case. These need to be invoiced before submission", CommonDialog.CustomDialogIcons.Information, "UnInvoiced Cases")
                        Exit Function
                    End If

                    If myData.Rows(0).Item("netinv") = 0 Then
                        If GlobalCRM.CurrentConID = 155 Or GlobalCRM.CurrentConID = 3 Then
                            'MJG 02-08-06 If me or Liam, then we are allowed to proceed
                            If MsgBox("Warning Zero invoice val.  Do you wish to proceed?", vbExclamation + vbYesNo, "Warning") = vbNo Then
                                Exit Function
                            End If
                        Else
                            CommonFuncs.DisplayMessage("Zero invoiced value, cannot submit", CommonDialog.CustomDialogIcons.Information, "Invoice")
                            Exit Function
                        End If
                    End If

                    If myData.Rows(0).Item("Balance") > 0.1 Then

                        If CommonDataFunctions.CSec(48) = 1 Then 'submit with funds outstanding
                            If MsgBox("This case still has funds OS, which should normally be paid before submission. Do you want to advance the case anyway?", vbYesNo + vbExclamation, "Admin Overide") <> MsgBoxResult.Yes Then
                                Exit Function
                            Else
                                CurSubOSAdmin = myData.Rows(0).Item("Balance")
                            End If
                        Else
                            'This functionality has been commented as requested buy Monika and approved by Liam - Date : 29/07/2008 - By:
                            'MsgBox("Cannot submit, there is " & strCurrencyChar & myData.Rows(0).Item("Balance") & " outstanding on this case", MsgBoxStyle.Exclamation, "Outstanding")
                            'Exit Function
                        End If
                    End If

                    myData.Dispose()
                End If

                'Check Doc Reqs

                myData = CRM.BusinessLayer.Documents.OutstandingDocs(CaseID)


                If myData.Rows.Count > 0 Then
                    Dim myRow As DataRow
                    Msg = New StringBuilder

                    If myData.Rows.Count > 1 Then

                        Msg.Append("The following documents requirements have not been marked as received." & vbCrLf & vbCrLf)

                        For Each myRow In myData.Rows
                            Msg.Append(myRow.Item("Docreq_Type") & ", " & myRow.Item("Docreq_name") & vbCrLf)
                        Next
                    Else

                        Msg.Append("The following document reqirement has not been marked as received." & vbCrLf & vbCrLf)
                        Msg.Append(myData.Rows(0).Item("Docreq_Type") & ", " & myData.Rows(0).Item("Docreq_name"))
                    End If

                    Msg.Append(vbCrLf & vbCrLf & "Do you want to submit anyway?")

                    If MsgBox(Msg.ToString, vbYesNo + vbExclamation, "Requirements Outstanding") <> MsgBoxResult.Yes Then
                        Exit Function
                    End If

                    tsk.GblFunc_Add_Event("Submitted with Doc Reqs Outstanding", Msg.ToString, 0, CaseID, TasksEvents.EventTypes.EventCase)

                End If

                myData.Dispose()
            End If

            'end of Authority submit Validation

            'Check if application has been granted and if so prompt for an expiry date where necesary. 180 = WP
            'WP Moved to file closed.

            'End of App granted validation

            'If refusal then


            If StageLinkTo = 170 Then
                Reason = InputBox("Please enter a brief reason for the cancellation/refusal", StageLinkDescription.Trim)
                If Reason.Trim = String.Empty Then
                    CommonFuncs.DisplayMessage("Cannot close without a reason", CommonDialog.CustomDialogIcons.Information, "Reason")
                    Exit Function
                End If

            End If

            'End of refusal checks

            'If Closing case then check financials.

            If StageLinkTo > 999 Then

                If myCaseInfo.CaseStatusId > 99 Then
                    'Only check for sold cases

                    'Have all charges been invoiced?
                    If Accounts.HasUninvoicedCharges(CaseID) Then
                        CommonFuncs.DisplayMessage("There are uninvoiced charges on this case! Before you can close the case, this needs to either be invoiced or deleted", CommonDialog.CustomDialogIcons.Information, "UnInvoiced")
                    End If
                End If
                'MG 7/7/07
                'End If

                'check balance of case
                Dim CaseBalance As Decimal = Accounts.GetCaseBalance(CaseID)
                Dim blnContinueFinance As Boolean = False
                If Not (CaseBalance > -0.1 And CaseBalance < 0.1) Then
                    If CaseBalance < 0 Then
                        If MsgBox("Case balance not zero." & vbCrLf & vbCrLf & "We owe the customer " & strCurrencyChar & CaseBalance * -1 & ", please check the finance screen for details.Would you still like to close the case?", MsgBoxStyle.YesNo, "Case Balance") = MsgBoxResult.Yes Then
                            blnContinueFinance = True
                        Else
                            Exit Function
                        End If
                    Else
                        CommonFuncs.DisplayMessage("Case balance not zero, cannot close." & vbCrLf & vbCrLf & "The customer owes us " & strCurrencyChar & CaseBalance & ", please check the finance screen for details.", CommonDialog.CustomDialogIcons.Information, "Case Balance")
                    End If
                    If blnContinueFinance = False Then
                        Exit Function
                    End If
                    'End
                    If True Then

                    End If

                End If
                'Check if Expiry date needs to be entered and whether current visa should be updated
                If StageLinkTo = 1000 Then 'And (IntProductType = 1 Or IntProductType = 2) Then

                    NoExpiry = 1

                    'Check if this is an indefinite product (i.e no expiry date required)
                    myProduct = Products.GetProductInfo(myCaseInfo.Productid)

                    If IsNothing(myProduct) Then
                        CommonFuncs.DisplayMessage("Error State. Cant find product for indefinite check", CommonDialog.CustomDialogIcons.Information, "Product")
                        Exit Function
                    End If

                    If Not myProduct.IndefiniteLeave Then



                        'Keep looping till they provide a valid date
                        Do

                            'See if there is already an expirty date

                            ExpiryDate = InputBox("Please enter the new expiry date" & vbCrLf & "(For EC cases please estimate)", "Expiry date", cmn.FormatDate(myCaseInfo.ExpiryDate))

                            If ExpiryDate.Trim = String.Empty Then
                                'no date provided

                                If CommonDataFunctions.CSec(10) = 1 Then
                                    'check for admin overide

                                    If MsgBox("Expiry date needs to be entered to close the file, are you sure you want to leave this blank? You should only select yes if we cannot get the expiry date for some reason.", vbYesNo, "Admin overide") = MsgBoxResult.Yes Then
                                        'admin overide, store for later and proceed
                                        NoExpiry = 2
                                    Else
                                        'cancel advance
                                        CommonFuncs.DisplayMessage("File close cancelled, please find out the expiry date and try again", CommonDialog.CustomDialogIcons.Information, "Expiry date")
                                        Exit Function
                                    End If

                                Else
                                    'cancel advance
                                    CommonFuncs.DisplayMessage("Cannot close the file without providing an expiry date", CommonDialog.CustomDialogIcons.Information, "Expiry date")
                                    Exit Function
                                End If
                            Else
                                'validate date and store for later
                                If Not IsDate(ExpiryDate) Then
                                    CommonFuncs.DisplayMessage("That is not a valid date, please try again", CommonDialog.CustomDialogIcons.Information, "Date Validation")
                                Else
                                    If CDate(ExpiryDate) < Now() Then
                                        CommonFuncs.DisplayMessage("Expiry date cannot be in the past, please try again", CommonDialog.CustomDialogIcons.Information, "Past date")
                                    Else
                                        ExpiryDate = cmn.FormatDate(ExpiryDate)
                                        NoExpiry = 0
                                    End If

                                End If

                            End If

                        Loop While NoExpiry = 1
                    End If

                End If


                'Confirmations and CFF data

                If StageLinkTo = 1000 Then
                    'Normal success close, just confirm
                    If MsgBox("Are you sure you wish to close this case?", vbYesNo, "Confirm") <> MsgBoxResult.Yes Then
                        Exit Function
                    Else
                        'close the tasks associated to this case - 
                        CommonDataFunctions.CompleteTasksForCase(myCaseInfo.CaseId)
                    End If
                Else
                    'Cancelled or refused, prompt for details
                    Reason = InputBox("Please enter a brief reason for the cancellation/refusal", StageLinkDescription)

                    If Reason.Trim = String.Empty Then
                        CommonFuncs.DisplayMessage("Cannot close without a reason", CommonDialog.CustomDialogIcons.Information, "Action cancelled")
                        Exit Function
                    Else
                        'close the tasks associated to this case - 
                        CommonDataFunctions.CompleteTasksForCase(myCaseInfo.CaseId)
                    End If
                End If

                'MG 7/7/7
            End If



            'end of case closed checks

            'Case On hold Checks
            Dim blnHoldTakeoff As Boolean = False
            If myCaseInfo.OnHold And StageLinkTo <> 999 Then
                If MsgBox("This case is on hold, advancing the stage will automaticaly remove this. Continue?", vbYesNo + vbExclamation, "Confirm Advance") <> MsgBoxResult.Yes Then
                    blnHoldTakeoff = False
                    Exit Function
                Else
                    blnHoldTakeoff = True
                End If
            End If


            'IntHold = 0
            'End If

            If Not myCaseInfo.OnHold And StageLinkTo = 999 Then
                If MsgBox("Would you like to place this case on hold as well?", vbYesNo + vbQuestion, "Place on Hold?") = MsgBoxResult.Yes Then
                    myCaseInfo.OnHold = True
                End If

            End If

            'End of Case on Hold Checks
            'Check if a Date update is going to be required

            'DB.BeginTrans()

            'FUCKED!!!

            Dim myStageInfo As Cases.CaseStageLookupItem = Cases.GetCaseStageLookup(StageLinkTo)

            If Not IsNothing(myStageInfo) Then

                If myStageInfo.DateColumn.Trim <> "" And Not myStageInfo.DateOverwite Then
                    'There is a date to update which shouldn't be overwritten, check if it's already been entered for this case

                    Dim DtUpdate As Object

                    DtUpdate = CommonDataFunctions.GetSQLScalar("Select " & myStageInfo.DateColumn.Trim & " From D_Case where Case_ID = " & myCaseInfo.CaseId)

                    If Not IsDBNull(DtUpdate) Then

                        'That column already has a value, cancel update
                        myStageInfo.DateColumn = String.Empty
                    End If
                End If
            End If

            'End up date update check


            'End of checks and validation.


            'Update the main case record

            'Primary update of status and DT Status
            If AdvanceType = 2 And StageLinkTo = 710 Then
                'If frmMainDisplay.Label53.Text = string.Empty Then
                CommonFuncs.DisplayMessage("Could not advance to next stage as the Document requested date is not set." & vbCrLf & "Please update the date of document requested and try again", CommonDialog.CustomDialogIcons.Information, "Error")
                'DB.RollbackTrans()
                Exit Function
                'End If
            End If

            SQL = New StringBuilder
            With SQL
                .Append("UPDATE D_Case ")
                .Append(" SET Case_StatusId = " & StageLinkTo & ", Case_DTStatus = '" & cmn.FormatDate(Now, True) & "'")

                'Optional updates based on advance type

                'Is there a date column to update?
                If myStageInfo.DateColumn.Trim <> "" Then
                    .Append(", " & myStageInfo.DateColumn & " = getdate()")
                End If

                'App granted and expiry date provided
                If StageLinkTo = 1000 And NoExpiry = 0 Then
                    .Append(",Case_DTExpiry = '" & cmn.FormatDate(myCaseInfo.ExpiryDate) & "'")
                End If
                ''
                ''
                'Place on/off hold if set earlier
                'If IntHold <> IntActiveStatus Then
                If blnHoldTakeoff = True Then
                    .Append(", Case_ActiveStatus = " & 0)
                    blnHoldTakeoff = False
                Else

                    .Append(", Case_ActiveStatus = " & IIf(myCaseInfo.OnHold = True, 1, 0))
                End If
                'End If
                ''
                ''
                'End of optional updates

                .Append(" WHERE Case_ID = " & CaseID)
            End With

            If Not CommonDataFunctions.ExecuteSQL(SQL.ToString) Then
                CommonFuncs.DisplayMessage("Error state. Update failed", CommonDialog.CustomDialogIcons.Information, "case Stage")
                '                DB.RollbackTrans()
                Exit Function
            End If

            'Main Update successfull
            '- Send email after case navigation
            'Done adding secondary case
            'Logic to send email -  - 25032008
            'GblFunc_Get_Dataset(CaseID, 1)


            'Commented - Liam's advise - 19092008 - 
            'blnAmendDataBeforeEmail = False
            If StageLinkTo = 100 Then
                frmPaymentPlan = New frmPaymentPlan
                frmPaymentPlan.ShowDialog()
                If frmCRMMainDisplay.blnCancelPaymentPlan = True Then

                    blnCancelPaymentPlan = False
                    SQL = New StringBuilder
                    With SQL
                        .Append("UPDATE D_Case ")
                        .Append(" SET Case_StatusId = " & myCaseInfo.CaseStatusId & ", Case_DTStatus = '" & cmn.FormatDate(Now, True) & "'")
                        If myStageInfo.DateColumn.Trim <> "" Then
                            .Append(", " & myStageInfo.DateColumn & " = getdate()")
                        End If
                        If StageLinkTo = 1000 And NoExpiry = 0 Then
                            .Append(",Case_DTExpiry = '" & cmn.FormatDate(myCaseInfo.ExpiryDate) & "'")
                        End If
                        .Append(", Case_ActiveStatus = " & IIf(myCaseInfo.OnHold = True, 1, 0))
                        .Append(" WHERE Case_ID = " & CaseID)
                    End With
                    If Not CommonDataFunctions.ExecuteSQL(SQL.ToString) Then
                        CommonFuncs.DisplayMessage("Failed to regain back to the original case stage" & vbCrLf & "Please contact IT", CommonDialog.CustomDialogIcons.Information, "case Stage")
                        '                        DB.RollbackTrans()

                        Exit Function
                    End If
                    'add event before exiting the function - 


                    Exit Function
                Else
                    'frmPaymentPlan.ShowDialog()
                End If
            End If
            If StageLinkTo >= 100 And StageLinkTo < 1000 Then
                CommonDataFunctions.CompleteTasksForCase_StageNavigation(GlobalCRM.CurrentCaseID)
            End If
            Dim TemplateID As Long
            If DiagramId = 1 And myPerson.PersonId > 0 Then
                ' If blnCancelEmail = False Then
                TemplateID = CommonDataFunctions.GetEmailTemplateID(myStageInfo.StageNumber, myCaseInfo.CaseStatusId, DiagramId)

                If TemplateID > 0 Then
                    Dim blnEmailSuccess As Boolean = False
                    'blnEmailSuccess ='
                    ' SendEmailToClient(myCaseInfo, myStageInfo, myPerson, TemplateID)
                    'SendEmailToClient(myCaseInfo, myStageInfo, myPerson, True)

                    If SendEmailToClient(myCaseInfo, myStageInfo, myPerson, TemplateID) = False Then
                        SQL = New StringBuilder
                        With SQL
                            .Append("UPDATE D_Case ")
                            .Append(" SET Case_StatusId = " & myCaseInfo.CaseStatusId & ", Case_DTStatus = '" & cmn.FormatDate(Now, True) & "'")
                            If myStageInfo.DateColumn.Trim <> "" Then
                                .Append(", " & myStageInfo.DateColumn & " = getdate()")
                            End If
                            If StageLinkTo = 1000 And NoExpiry = 0 Then
                                .Append(",Case_DTExpiry = '" & cmn.FormatDate(myCaseInfo.ExpiryDate) & "'")
                            End If
                            .Append(", Case_ActiveStatus = " & IIf(myCaseInfo.OnHold = True, 1, 0))
                            .Append(" WHERE Case_ID = " & CaseID)
                        End With
                        If Not CommonDataFunctions.ExecuteSQL(SQL.ToString) Then
                            CommonFuncs.DisplayMessage("Failed to regain back to the original case stage" & vbCrLf & "Please contact IT", CommonDialog.CustomDialogIcons.Information, "case Stage")
                            '                        DB.RollbackTrans()

                            Exit Function
                        End If
                        'add event before exiting the function - 


                        Exit Function
                    End If
                    'End If
                    'SendEmailToClient(myCaseInfo, myStageInfo, myPerson, True)
                End If
            End If

            'Commented till this -  - 19092008
            'Audit
            Gblfunc_Add_CaseAudit(CaseID, 6, myCaseInfo.CaseStatusId, StageLinkTo, GlobalCRM.CurrentConID)

            'Add or amend any other records as required.
            '
            'If this is a sold case being cancelled or refused then add a CFF
            If StageLinkTo = 1010 Or StageLinkTo = 170 Then
                'Cancelled or Refused, add a CFF.
                Cases.AddCFF(CaseID, StageLinkTo, Reason, GlobalCRM.CurrentConName)
            End If

            'Update Personal Expiry Date and current visa as required
            If myPerson.PersonId > 0 Then
                If StageLinkTo = 1000 Then

                    If myCaseInfo.CandidateId = 0 Then
                        'Error State
                        CommonFuncs.DisplayMessage("Could not find candidate from case when updating exipiry date/current Visa", CommonDialog.CustomDialogIcons.Information, "Error")
                        '                        DB.RollbackTrans()
                        Exit Function
                    End If


                    Select Case NoExpiry

                        Case 0
                            'New Expiry date to set

                            Msg = New StringBuilder

                            If Not IsDate(myPerson.UKVisaExpiry) Then
                                Msg.Append("Expiry Date changed from blank to " & myPerson.UKVisaExpiry & " with completion of case " & CaseID)
                            Else
                                Msg.Append("Expiry Date changed from " & myPerson.UKVisaExpiry & " to " & ExpiryDate & " with completion of case " & CaseID)
                            End If

                            People.UpdateVisaExpiryDate(myPerson.PersonId, Date.Parse(myPerson.UKVisaExpiry), Msg.ToString)

                        Case 1
                            'Indefinite Visa, set to null
                            Msg = New StringBuilder

                            If Not IsDate(myPerson.UKVisaExpiry) Then
                                Msg.Append("Expiry Date changed from blank to Indefinite (Blank) with completion of case " & CaseID)
                            Else
                                Msg.Append("Expiry Date changed from " & myPerson.UKVisaExpiry & " to Indefinite (Blank) with completion of case " & CaseID)
                            End If

                            People.UpdateVisaExpiryDate(myPerson.PersonId, Date.Parse(myPerson.UKVisaExpiry), Msg.ToString)

                        Case 2
                            'Admin overide, do nothing

                    End Select

                    'Current Visa

                    If myProduct.UKVisaId > 0 Then

                        Msg = New StringBuilder

                        If myPerson.UKVisaId > 0 Then
                            Msg.Append("UK Visa changed from " & myPerson.UKVisaName.Trim & " to " & myProduct.UKVisaName)
                        Else
                            Msg.Append("UK Visa changed from blank to " & myProduct.UKVisaName)
                        End If

                        If Not People.UpdateVisaType(myPerson.PersonId, myProduct.UKVisaId, Msg.ToString) Then
                            '                            DB.RollbackTrans()
                            Exit Function
                        End If

                    End If
                End If
            End If

            'Secondary updates successfull

            'Set the message for the event
            CurrentStage = Cases.GetCaseStageLookup(myCaseInfo.CaseStatusId).StageTitle

            Msg = New StringBuilder

            Msg.Append("Case status changed from " & CurrentStage & " to " & StageLinkDescription)

            If CurSubOSAdmin > 0 Then
                Msg.Append(vbCrLf & strCurrencyChar & CurSubOSAdmin & " OS on case, but admin overide used to submit")
            End If

            If Not IsNothing(Reason) Then
                If Reason.Trim <> "" Then
                    Msg.Append(vbCrLf & vbCrLf & "Reason for cancellation/refusal" & vbCrLf & Reason)
                End If
            End If

            'Add hold cancelled event first if req
            If myCaseInfo.OnHold <> ActiveStatus And Not myCaseInfo.OnHold Then
                tsk.GblFunc_Add_Event("Hold Cancelled", "Hold Cancelled", 1, CaseID, TasksEvents.EventTypes.EventCase)
            End If

            'Messge set, add event

            If myStageInfo.StageNumber = 1030 Or myStageInfo.StageNumber = 1040 Then
                tsk.GblFunc_Add_Event("Lead Cancelled", Msg.ToString, 1, CaseID, TasksEvents.EventTypes.EventCase, 0, StageLinkKeyDate)
            Else
                tsk.GblFunc_Add_Event(StageLinkDescription, Msg.ToString, 1, CaseID, TasksEvents.EventTypes.EventCase, 0, StageLinkKeyDate)
            End If

            'Add put on hold event now if req
            If myCaseInfo.OnHold <> ActiveStatus And myCaseInfo.OnHold Then
                tsk.GblFunc_Add_Event("Case placed On Hold", "Case placed On Hold", 1, CaseID, TasksEvents.EventTypes.EventCase)
            End If

            If StageLinkTo > 100 And myCaseInfo.CaseWorkerId > 0 Then
                'TasksEvents.GblFunc_Add_Event("Case Review", "Review Case " & CStr(CaseID), TasksEvents.EventStatus.Task, myCaseInfo.CaseId, CommonSQL.EventTypes.EventCase, , , myCaseInfo.CaseWorkerId, AddWorkingDays(Now, 3))
            End If

            If StageLinkTo > 100 And myCaseInfo.CaseCoordinatorID > 0 Then
                'TasksEvents.GblFunc_Add_Event("Case Review", "Review Case " & CStr(CaseID), TasksEvents.EventStatus.Task, myCaseInfo.CaseId, CommonSQL.EventTypes.EventCase, , , myCaseInfo.CaseCoordinatorID, AddWorkingDays(Now, 3))
            End If

            If AddSecondCase > 0 Then
                'Work out Sales Consulatant if not already retrieved from main case

                Dim myCompany As Company.CompanyInfo = Company.GetCompany(myCaseInfo.CompanyId)

                If myCaseInfo.SalesConid = 0 Or myCaseInfo.SalesConid = 11 Then


                    If myCaseInfo.CompanyId > 0 Then
                        SalesConId = myCompany.AccountManagerId
                    Else
                        If myPerson.PersonId > 0 Then
                            SalesConId = myPerson.AccountManagerId
                        End If
                    End If

                    If SalesConId = 0 Then
                        SalesConId = 11
                    End If

                End If

                If myCaseInfo.CaseWorkerId = 0 Then
                    myCaseInfo.CaseWorkerId = 11
                End If

                'If no CW retrieved above and corporate, see if there's a default for the account.
                If myCaseInfo.CaseWorkerId = 11 And myCaseInfo.CompanyId > 0 Then
                    If myCompany.DefaultCaseWorker > 0 Then
                        myCaseInfo.CaseWorkerId = myCompany.DefaultCaseWorkerId
                    End If
                End If

                Dim myNewCase As New Cases.CaseInfo

                With myNewCase
                    .EnteredBy = GlobalCRM.CurrentConName
                    .Productid = AddSecondCase
                    .SalesConid = myCaseInfo.SalesConid
                    .CaseWorkerId = myCaseInfo.CaseWorkerId
                    .CompanyId = myCaseInfo.CompanyId
                    .CaseStatusId = 100
                    .SoldDate = Now
                    .CandidateId = myCaseInfo.CandidateId
                    .Contactid = myCaseInfo.Contactid
                    .PrimaryCaseId = myCaseInfo.CaseId
                End With

                myNewCase.CaseId = Cases.CreateNewCase(myNewCase)

                If myNewCase.CaseId = 0 Then
                    '                    DB.RollbackTrans()
                    Exit Function
                End If

                If Not Cases.CreateNewCaseDocReqs(myNewCase.CaseId, GlobalCRM.CurrentConName, myNewCase.Productid) Then
                    '                    DB.RollbackTrans()
                    Exit Function
                End If

                tsk.GblFunc_Add_Event("Secondary Case", "This case is a secondary application related to case number " & CaseID, 0, myNewCase.CaseId, TasksEvents.EventTypes.EventCase)

                '75 = UK FLR
                '20 = UK EC
                '209 = UK FLR (FT)

                Msg = New StringBuilder

                Select Case AddSecondCase
                    'add primary case id into case table column
                    Case 75
                        Msg.Append("UK FLR application added as secondary case number " & myNewCase.CaseId)

                    Case 20
                        Msg.Append("UK Entry Clearance application added as secondary case number " & myNewCase.CaseId)

                    Case 209
                        Msg.Append("UK FLR (Fast Track) application added as secondary case number " & myNewCase.CaseId)

                End Select

                tsk.GblFunc_Add_Event("Secondary Case Added", Msg.ToString, 0, CaseID, TasksEvents.EventTypes.EventCase)

                If myNewCase.CaseWorkerId > 0 Then
                    tsk.GblFunc_Add_Event("Case Review", "Review Case " & CStr(myNewCase.CaseId), TasksEvents.EventStatus.Task, myNewCase.CaseId, TasksEvents.EventTypes.EventPerson, , , myNewCase.CaseWorkerId, cmn.AddWorkingDays(Now, 3))
                End If

                If myNewCase.CaseCoordinatorID > 0 Then
                    tsk.GblFunc_Add_Event("Case Review", "Review Case " & CStr(myNewCase.CaseId), TasksEvents.EventStatus.Task, myNewCase.CaseId, TasksEvents.EventTypes.EventPerson, , , myNewCase.CaseCoordinatorID, cmn.AddWorkingDays(Now, 3))
                End If

            End If

            'MJG 16/10/06 If new case then generate user name and password

            If StageLinkTo < 1000 Then

                'Only generate user name / password if they are null

                If myPerson.PersonId > 0 Then
                    If myPerson.WebUserName.Trim = String.Empty Or myPerson.WebPassword.Trim = String.Empty Then
                        People.GenerateWebPassword(myCaseInfo.CandidateId)
                    End If
                End If

            End If

            If StageLinkTo = 100 Then
                ' - Check for the document check list availability and populate if the list is empty.
                Dim docSummary As DocumentsSummary = GetDocStoreSummary(GlobalCRM.CurrentCaseID)
                If docSummary.Required > 0 Then

                Else

                    tsk.GblFunc_Add_Event("Details Changed", "Default doc reqs loaded onto case" & vbCrLf, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, 1)

                    CRM.BusinessLayer.Documents.LoadDefaultDocuments(GlobalCRM.CurrentCaseID)
                End If
            End If
            'update case status history table
            '            CompleteTasksForCase_StageNavigation(GlobalCRM.CurrentCaseID)
            CommonDataFunctions.UpdateCaseStatus(myCaseInfo.CaseStageTitle, StageLinkDescription)
            CommonDataFunctions.UpdateCaseStatusNo(myCaseInfo.CaseStatusId, StageLinkTo)
            Return True
        Catch ex As Exception
            GblFunc_Advance_CaseStage = False
            If CommonFuncs.IsTransactionOpen() Then
                'DB.RollbackTrans()
            End If
            'CommonFunc.ErrorHandler(ex, "CommonFunc.gblFunc_Advance_CaseStage")
        Finally
            frmPaymentPlan = Nothing
        End Try


    End Function
    Public Shared Function SendEmailToClient(ByVal mycaseInfo As Cases.CaseInfo, ByVal mystageInfo As Cases.CaseStageLookupItem, ByVal myPerson As People.PersonInfo, ByVal TemplateID As Long, Optional ByVal blnAlternative As Boolean = False) As Boolean
        'Dim db As New CRM.DataLayer.DataAccess
        Dim tsk As New TasksEvents
        Dim cmn As New CommonFuncs
        Try
            Dim blnHidePopup As Boolean = False
            Dim sqlbldr As New StringBuilder
            Dim EmailFrom As String
            Dim strTemp As String
            Dim Attach As GlobalCRM.LocalAttachments.LocalAttachment
            Dim DocStoreId As Long
            ' Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
            'Dim TemplateID As Integer
            Dim attachnames As StringBuilder
            'Select - case for appropriate case advancement
            Dim blnSignature As Boolean = True
            'frmEmailCaseNavigation.btnCancel.Visible = True
            Dim blnToLoginArea As Boolean = False

            ' TemplateID = GetEmailTemplateID(mystageInfo.StageNumber, mycaseInfo.CaseStatusId, DiagramId)
            If TemplateID > 0 Then
                If mystageInfo.StageNumber > 100 And mystageInfo.StageNumber <= 999 Then
                    blnToLoginArea = True
                End If
                'Dim EmailFrom As String
                Dim EmailTo As String = String.Empty
                Dim test As Singleton = Singleton.Instance
                If EmailFrom = String.Empty Then
                    sqlbldr.Append("Select Con_EMail from L_Consultant where Con_ID = " & test.CurrentConId)
                    EmailFrom = CommonDataFunctions.GetSQLScalar(sqlbldr.ToString)
                End If
                If EmailFrom Is Nothing Then
                    MsgBox("Your email id is not updated in the database." & vbCrLf & "Please contact IT", MsgBoxStyle.Critical, "Email Not sent")
                    Return False
                End If

                Dim DataType As Integer
                Dim DataID As Long
                If GlobalCRM.CurrentCompanyID = 0 Then
                    DataType = 1
                    DataID = mycaseInfo.CaseId
                    sqlbldr = New StringBuilder
                    sqlbldr.Append("Select EmailAddress_Address from D_EmailAddress where EmailAddress_personID = " & myPerson.PersonId)
                    EmailTo = CommonDataFunctions.GetSQLScalar(sqlbldr.ToString)
                    If EmailTo Is Nothing Then
                        MsgBox("The Email address of the client is not found in the system. Hence email has not been sent", MsgBoxStyle.OkOnly, "Email Not sent")
                        Return False
                    End If
                Else
                    DataType = 3
                    DataID = GlobalCRM.CurrentCompanyID
                    sqlbldr = New StringBuilder
                    sqlbldr.Append("SELECT     dbo.D_EmailAddress.EMailAddress_Address FROM   dbo.D_Case INNER JOIN   dbo.D_EmailAddress ON dbo.D_Case.Case_ContactID = dbo.D_EmailAddress.EMailAddress_PersonID WHERE     (dbo.D_Case.Case_ID = " & GlobalCRM.CurrentCaseID & ")")
                    EmailTo = CommonDataFunctions.GetSQLScalar(sqlbldr.ToString)
                    If EmailTo Is Nothing Then
                        MsgBox("The Email address of the client is not found in the system. Hence email has not been sent", MsgBoxStyle.OkOnly, "Email Not sent")
                        Exit Function
                    End If
                End If
                Dim dt As System.Data.DataTable

                Dim myTemplate As CommonDataFunctions.EmailTemplateInfo
                myTemplate = CommonDataFunctions.GetEmailTemplate(TemplateID)
                If Not myTemplate.Body Is Nothing And Not myTemplate.SubjectLine Is Nothing And Not myTemplate.TemplateName Is Nothing Then
                    Dim StrSQLBookmarks As String = String.Empty
                    Dim intCount As Integer = 1
                    Dim txtfile As String = System.IO.Path.GetTempPath & "CRMTemp\sample.txt"
                    Directory.CreateDirectory(System.IO.Path.GetTempPath & "CRMTemp")

                    Dim oWrite As System.IO.StreamWriter
                    oWrite = File.CreateText(System.IO.Path.GetTempPath & "CRMTemp\sample.txt")
                    oWrite.Write(myTemplate.Body)
                    oWrite.Close()

                    Dim oRead As System.IO.StreamReader
                    Dim LineIn As String
                    Dim strNew() As String
                    Dim strnew1() As String
                    Dim i As Integer
                    Dim c As New Microsoft.VisualBasic.Collection
                    Dim cData As Microsoft.VisualBasic.Collection = Nothing
                    Dim cIndex As New Microsoft.VisualBasic.Collection
                    Dim bln As Boolean
                    oRead = IO.File.OpenText(txtfile)
                    While oRead.Peek <> -1
                        LineIn = oRead.ReadLine()
                        strNew = Split(LineIn, "<")
                        For i = 0 To strNew.Length - 1
                            strnew1 = Split(strNew(i).ToString, ">")
                            If strnew1.Length > 1 Then
                                'StrSQLBookmarks = strnew1(0).ToString
                                StrSQLBookmarks = StrSQLBookmarks & "'" & strnew1(0).ToString & "',"
                                If cIndex.Contains(strnew1(0).ToString) = False Then
                                    cIndex.Add(i, strnew1(0).ToString)
                                    bln = True
                                End If
                                If bln Then
                                    c.Add(strnew1(0).ToString)
                                End If
                                bln = False
                            End If
                        Next
                    End While
                    oRead.Close()

                    StrSQLBookmarks = Left(StrSQLBookmarks, (Len(StrSQLBookmarks) - 1))
                    StrSQLBookmarks = "(" & StrSQLBookmarks & ")"

                    Dim sql1 As New StringBuilder
                    With sql1
                        .Append("SELECT BookMark_Text as BMName")
                        .Append(" FROM I_SL_Bookmarks")
                        .Append(" WHERE Bookmark_Text in " & StrSQLBookmarks & "")
                        '.Append(" AND Bookmark_VersionID <= " & 1)
                        .Append(" GROUP BY BookMark_Text")
                    End With
                    dt = CommonDataFunctions.GetSQLDatatable(sql1.ToString)
                    If Not dt Is Nothing Then
                        If dt.Rows.Count > 0 Then
                            Dim StrBMData As String = ""
                            cData = New Microsoft.VisualBasic.Collection
                            For i = 0 To dt.Rows.Count - 1
                                ' So we can monitor value
                                strTemp = dt.Rows(i).Item("BMName")
                                If dt.Rows(i).Item("BMName") <> "" Then
                                    If GlobalCRM.CurrentCompanyID <> 0 Then
                                        If dt.Rows(i).Item("BMName") = "CandidateDearName" Then
                                            StrBMData = Letters.Gblfunc_Get_BookmarkData("ContactDearName", DataID, DataType)
                                            cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                        Else
                                            DataType = 1
                                            DataID = mycaseInfo.CaseId
                                            StrBMData = Letters.Gblfunc_Get_BookmarkData(dt.Rows(i).Item("BMName"), DataID, DataType)
                                            cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                        End If
                                    Else
                                        StrBMData = Letters.Gblfunc_Get_BookmarkData(dt.Rows(i).Item("BMName"), DataID, DataType)
                                        cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                    End If
                                End If
                                If StrBMData = "EmailError_IT_Contact" Then
                                    System.IO.File.Delete(txtfile)
                                    Directory.Delete(System.IO.Path.GetTempPath & "CRMTemp\")
                                    Exit Function
                                End If
                            Next
                        End If
                    End If
                    oRead = IO.File.OpenText(txtfile)
                    Dim strRep As String = oRead.ReadToEnd
                    oRead.Close()
                    Dim OpToEmail As String
                    For i = 1 To cData.Count
                        If OpToEmail = "" Then
                            OpToEmail = strRep.Replace("<" & c.Item(i) & ">", cData.Item(c.Item(i)))
                        Else
                            OpToEmail = OpToEmail.Replace("<" & c.Item(i) & ">", cData.Item(c.Item(i)))
                        End If
                    Next
                    'Dim subj As String = "Global Visas Case Update"
                    Dim Signature As String = ""
                    Dim singleTon As Singleton = singleTon.Instance
                    If blnSignature = False Then
                        Signature = vbCrLf & CommonDataFunctions.GblFunc_Get_Sigfile(GlobalCRM.CurrentConID, blnSignature)
                    Else

                        Signature = singleTon.CompanyNameInDisclaimer.ToUpper() & " TEAM" & vbCrLf & vbCrLf & CommonDataFunctions.GblFunc_Get_Sigfile(GlobalCRM.CurrentConID, blnSignature)
                    End If
                    OpToEmail = OpToEmail & vbCrLf & Signature
                    'EMAILBCCSTRING
                    EMAILBODYSTRING = OpToEmail
                    EMAILSUBJECTSTRING = GlobalCRM.subj
                    EMAILFROMSTRING = EmailFrom
                    EMAILTOSTRING = EmailTo


                    If (contentOfButtonPressed = "CCL SENT") Then
                        Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
                        Dim cclAutomation = CType(configurationAppSettings.GetValue("cclAutomation", GetType(System.String)), String)
                        If (cclAutomation.ToUpper = "TRUE") Then
                            ' create the ccl proforma and attach them in globalcrm.lo  GlobalCRM.LocalAttachments.Attachments
                            Dim singleObject As Singleton = Singleton.Instance
                            Dim directoryInfo As DirectoryInfo = Directory.CreateDirectory("C:\Temp\" & singleObject.CurrentConName)
                            For Each fileNameWithPath As String In Directory.GetFiles("C:\Temp\" & singleObject.CurrentConName)
                                File.Delete(fileNameWithPath)
                            Next
                            Dim totalInvoice As String = String.Empty
                            CreateCCL(directoryInfo, totalInvoice)
                            CreateContract(directoryInfo, totalInvoice)
                        End If
                    End If

                    Dim frmEmailCaseNavigation As New frmEmailCaseNavigation
                    frmEmailCaseNavigation.txtEmailBody.IsEnabled = True
                    frmEmailCaseNavigation.txtSubject.IsEnabled = True
                    'End If
                    If blnHidePopup = False Then
                        frmEmailCaseNavigation.ShowDialog()
                    Else
                        blnAmendDataBeforeEmail = False
                    End If
                    If blnAmendDataBeforeEmail Then 'And blnHidePopup = False Then
                        Exit Function
                    ElseIf blnCancelEmail Then
                        blnCancelEmail = False
                        Exit Function
                    Else
                        attachnames = New StringBuilder
                        If GlobalCRM.LocalAttachments.Attachments.Count > 0 Then
                            'Add files to Docstore then pass Docstore ID to the mail engine
                            DocStoreId = Letters.GblFunc_Create_DocStore("Files E-Mailed", "Documents E-Mailed", GlobalCRM.CurrentCaseID, 1)
                            For Each Attach In GlobalCRM.LocalAttachments.Attachments

                                If Letters.GblFunc_Add_FileToStore(Attach.Filepath, Strings.Left(Attach.Name, 99), DocStoreId) = 0 Then
                                    MsgBox("Couldn't find attachment file, send failed", MsgBoxStyle.Critical)
                                    Exit Function
                                End If

                                attachnames.Append(Attach.Filepath)
                                attachnames.Append(vbCrLf)
                            Next
                        End If
                        If blnToLoginArea = False Then
                            CommonDataFunctions.SendEmailToClient(mycaseInfo, mystageInfo, myPerson, 1)
                            'Dim Success As Integer = Letters.GblFunc_Send_MailEngine(EMAILTOSTRING, EMAILFROMSTRING, EMAILSUBJECTSTRING, EMAILBODYSTRING, , EMAILBCCSTRING, DocStoreId)

                            'Dim Msg As New StringBuilder
                            'With Msg
                            '    .Append("Email Sent" & vbCrLf & vbCrLf & "To: " & EmailTo)

                            '    .Append(vbCrLf & vbCrLf & "Sent via mail engine")
                            '    .Append(vbCrLf & "Subject: " & GlobalCRM.subj)
                            '    .Append(vbCrLf & "Attachments : " & attachnames.ToString)
                            '    .Append(vbCrLf & "Message: " & vbCrLf & vbCrLf & EMAILBODYSTRING)
                            'End With
                            'EMAILSUBJECTSTRING = ""
                            'EMAILBODYSTRING = ""
                            'EMAILBCCSTRING = ""
                            'tsk.GblFunc_Add_Event("Send Email", Msg.ToString, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , 1)
                            'If Success = 1 Then
                            '    MsgBox("Email has been sent to the client successfully.", MsgBoxStyle.Information, "Success")
                            'End If
                            GlobalCRM.LocalAttachments.Attachments.Clear()
                            'System.IO.File.Delete(txtfile)
                            'cmn.ForceDeleteTempDir()
                        Else
                            Dim candid As Long = 0
                            If GlobalCRM.CurrentCompanyID = 0 Then
                                candid = GlobalCRM.CurrentCandidateID
                            ElseIf GlobalCRM.CurrentCompanyID > 0 Then
                                If GlobalCRM.CurrentContactID > 0 Then
                                    candid = GlobalCRM.CurrentContactID
                                Else
                                    candid = GlobalCRM.CurrentCandidateID
                                End If
                            End If
                            'Login Area
                            If Letters.SendMailMessage(EMAILTOSTRING, GlobalCRM.CurrentConID, GlobalCRM.CurrentCaseID, EMAILSUBJECTSTRING, EMAILBODYSTRING, candid, EMAILBCCSTRING) = 0 Then
                                'Me.btnSend.Enabled = True
                                MsgBox("Error. Message could not be added to the S_SendEmail table.")
                                Exit Function
                            Else
                                'Dim msgbody As StringBuilder

                                CommonDataFunctions.SendEmailToClient_ForLoginArea(GlobalCRM.CurrentCandidateID, CommonDataFunctions.EmailType.Candidate)

                                tsk.GblFunc_Add_Event("Send Email", "The email has been sent to the client and is viewable through login Area : " & vbCrLf & "Subject :" & EMAILSUBJECTSTRING & vbCrLf & "Body :" & vbCrLf & EMAILBODYSTRING, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , 1)
                                Try


                                    GlobalCRM.LocalAttachments.Attachments.Clear()

                                    'delete the draft
                                    ' Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
                                    'GlobalCRM.LocalAttachments.Attachments.Clear()
                                    'System.IO.File.Delete(txtfile)
                                    'cmn.ForceDeleteTempDir()
                                Catch ex As Exception

                                End Try
                                '                End If
                            End If

                        End If
                    End If
                End If
            End If
            Return True
        Catch ex As Exception
            ' CommonFunc.ErrorHandler(ex, "CommonFunc.SendEmailToClient", True)
            Return False
        Finally

            tsk = Nothing
            cmn = Nothing
        End Try
    End Function

    Private Shared Sub CreateCCL(ByVal directoryInfo As DirectoryInfo, ByRef totalInvoice As String)
        Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
        Dim proformaFileName = CType(configurationAppSettings.GetValue("proformaFileName", GetType(System.String)), String)
        Dim singleObject As Singleton = Singleton.Instance
        Dim fileName As String = proformaFileName.Replace(".pdf", "")
        Dim pdfFileName As String = proformaFileName
        Dim pdfFileNameWithCaseId As String = fileName & GlobalCRM.CurrentCaseID & ".pdf"
        Dim newPdFileCompleteName As String = String.Empty
        Dim outPutPdfFileName As String = directoryInfo.FullName & "\" & pdfFileNameWithCaseId
        Dim cclAutomationRequiresPdf As String = String.Empty
        Try
            newPdFileCompleteName = directoryInfo.FullName & "\" & fileName & ".pdf"
            If (File.Exists(newPdFileCompleteName)) Then
                File.Delete(newPdFileCompleteName)
            End If
            Dim inputDrive As String = CType(configurationAppSettings.GetValue("DocStoreServer", GetType(System.String)), String)
            File.Copy(inputDrive & "\" & pdfFileName, newPdFileCompleteName, True)
            SearchAndReplaceInvoiceBookMarks(newPdFileCompleteName, outPutPdfFileName, totalInvoice)
        Catch generatedException As Exception
            System.Windows.MessageBox.Show("Error in processing the invoice." & generatedException.Message, "Internal Error")
            Return
        Finally
            GC.Collect()
            GC.WaitForPendingFinalizers()
            GC.Collect()
            GC.WaitForPendingFinalizers()
        End Try
        GlobalCRM.LocalAttachments.AddAttachment(outPutPdfFileName, outPutPdfFileName)
    End Sub

    Private Shared Function SearchAndReplaceInvoiceBookMarks(ByVal inputPdfFileName As String, ByVal outputPdfFileName As String, ByRef totalInvoice As String)
        Dim originalFile As String = inputPdfFileName

        Dim copyOfOriginal As String = outputPdfFileName

        Using reader As New PdfReader(originalFile)

            Using stamper As New PdfStamper(reader, New System.IO.FileStream(copyOfOriginal, FileMode.OpenOrCreate))

                stamper.AcroFields.SetField("date", DateAndTime.Today.Day & "-" & DateAndTime.Today.Month & "-" & DateAndTime.Today.Year)
                stamper.AcroFields.SetField("caseid", GlobalCRM.CurrentCaseID)
                Dim dt As New System.Data.DataTable
                dt = CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID))
                Dim chargeType As String = String.Empty
                Dim netCharge, tax, total, sumTotal As Long
                Dim invoiceDetailsLiteral = String.Empty
                Dim dr As DataRow
                Dim pdfRowCounter = 0
                For counter As Integer = 0 To dt.Rows.Count - 1
                    dr = dt.Rows(counter)
                    chargeType = Convert.ToString(dr.Item("Charge_Type"))
                    netCharge = Convert.ToDouble(dr.Item("Charge_Amount"))
                    tax = Convert.ToDouble(dr.Item("Charge_VAT"))
                    total = Convert.ToDouble(dr.Item("ChgGross"))
                    sumTotal = sumTotal + total
                    pdfRowCounter = pdfRowCounter + 1
                    stamper.AcroFields.SetField("description" & pdfRowCounter, chargeType)
                    stamper.AcroFields.SetField("net" & pdfRowCounter, netCharge)
                    stamper.AcroFields.SetField("tax" & pdfRowCounter, tax)
                    stamper.AcroFields.SetField("total" & pdfRowCounter, total)

                Next
                stamper.AcroFields.SetField("totalfinal", sumTotal)
                totalInvoice = sumTotal
                For Each de As KeyValuePair(Of String, AcroFields.Item) In stamper.AcroFields.Fields
                    stamper.AcroFields.SetFieldProperty(de.Key.ToString(), "setfflags", PdfFormField.FF_READ_ONLY, Nothing)
                Next
            End Using

        End Using
    End Function

    Private Shared Sub CreateContract(ByVal directoryInfo As DirectoryInfo, ByVal totalInvoice As String)
        Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
        Dim workandLiveContractFileName = CType(configurationAppSettings.GetValue("workandLiveContractFileName", GetType(System.String)), String)
        Dim singleObject As Singleton = Singleton.Instance
        Dim fileName As String = workandLiveContractFileName.Replace(".pdf", "")
        Dim pdfFileName As String = workandLiveContractFileName
        Dim pdfFileNameWithCaseId As String = fileName & GlobalCRM.CurrentCaseID & ".pdf"
        Dim newPdFileCompleteName As String = String.Empty
        Dim outPutPdfFileName As String = directoryInfo.FullName & "\" & pdfFileNameWithCaseId
        Try
            newPdFileCompleteName = directoryInfo.FullName & "\" & fileName & ".pdf"
            If (File.Exists(newPdFileCompleteName)) Then
                File.Delete(newPdFileCompleteName)
            End If
            Dim inputDrive As String = CType(configurationAppSettings.GetValue("DocStoreServer", GetType(System.String)), String)
            File.Copy(inputDrive & "\" & pdfFileName, newPdFileCompleteName, True)
            SearchAndReplaceContractBookMarks(newPdFileCompleteName, outPutPdfFileName, totalInvoice)
        Catch generatedException As Exception
            System.Windows.MessageBox.Show("Error in processing the invoice." & generatedException.Message, "Internal Error")
            Return
        Finally
            GC.Collect()
            GC.WaitForPendingFinalizers()
            GC.Collect()
            GC.WaitForPendingFinalizers()
        End Try
        GlobalCRM.LocalAttachments.AddAttachment(outPutPdfFileName, outPutPdfFileName)

    End Sub

    Private Shared Function SearchAndReplaceContractBookMarks(ByVal inputPdfFileName As String, ByVal outputPdfFileName As String, ByVal totalInvoice As String)
        Dim originalFile As String = inputPdfFileName

        Dim copyOfOriginal As String = outputPdfFileName

        Using reader As New PdfReader(originalFile)

            Using stamper As New PdfStamper(reader, New System.IO.FileStream(copyOfOriginal, FileMode.OpenOrCreate))

                stamper.AcroFields.SetField("date", DateAndTime.Today.Day & "-" & DateAndTime.Today.Month & "-" & DateAndTime.Today.Year)
                stamper.AcroFields.SetField("caseid", GlobalCRM.CurrentCaseID)
                stamper.AcroFields.SetField("candidatename", GlobalCRM.CurrentCandidateName)
                Dim candidateAddress As String = People.GetAddressForContract(GlobalCRM.CurrentCandidateID)
                stamper.AcroFields.SetField("address", candidateAddress)

                Dim personInfo As PrivateIndividual.PersonInfo = PrivateIndividual.GetPerson(GlobalCRM.CurrentCandidateID)
                stamper.AcroFields.SetField("destination", personInfo.DestinationName)

                Dim productTypeName As String = Products.ProductTypeName(GlobalCRM.CurrentCaseID)
                stamper.AcroFields.SetField("producttype", productTypeName)
                stamper.AcroFields.SetField("totalamount", totalInvoice)
                'Date, caseid, candidatename , address ,product, producttype ,totalamount
                For Each de As KeyValuePair(Of String, AcroFields.Item) In stamper.AcroFields.Fields
                    stamper.AcroFields.SetFieldProperty(de.Key.ToString(), "setfflags", PdfFormField.FF_READ_ONLY, Nothing)
                Next
            End Using

        End Using
    End Function


    Private Sub AdvanceCaseStage(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnStage1.Click, btnStage2.Click, btnStage3.Click, btnStage4.Click, btnStage5.Click, btnStage6.Click
        Dim singleObject As Singleton = Singleton.Instance

        contentOfButtonPressed = CType(sender, Button).Content.ToString().ToUpper()
        If (CType(sender, Button).Content.ToString().ToUpper() = "CCL SENT") Then
            'validate at CCL sent so it tells you to add a qouted charge first
            Dim QuotedCharges As System.Data.DataTable = CommonDataFunctions.GetSQLDatatable(Accounts.QuotedCharges(GlobalCRM.CurrentCaseID))

            If (QuotedCharges.Rows.Count() > 0) Then
                'CCL client care letter adding this as a letter pack and entering bookmark for candidate name and product type and case fees (i.e the invoice entered) to be generated when a consultant presses the CCL sent button
                'Adding the pro forma invoice into the CRM with bookmark candidate name, product type and case fees to be generated when consultant presses CCL sent button
            Else
                MsgBox("Dear " & singleObject.CurrentConName & " , Please add Quoted charges first for : " & GlobalCRM.CurrentCaseID, MsgBoxStyle.Exclamation, "Error")
                Exit Sub
            End If

        End If

        If (CType(sender, Button).Content.ToString().ToUpper() = "OPEN FILE") Then
            ' validate if any payment has been added or not - if yes then proceed else raise the error message
            Dim payments As System.Data.DataTable = CommonDataFunctions.GetSQLDatatable(Accounts.Payments(GlobalCRM.CurrentCaseID))
            If (payments.Rows.Count() > 0) Then

            Else
                MsgBox("Dear " & singleObject.CurrentConName & " , case file cannot be opened as  there is no payment done for the case number : " & GlobalCRM.CurrentCaseID, MsgBoxStyle.Exclamation, "Error")
                Exit Sub
            End If
        End If

        CommonFuncs.BeginTrans()
        Dim caseStageFrom As Integer = Cases.GetCaseStage(GlobalCRM.CurrentCaseID).StageNumber
        If GblFunc_Advance_CaseStage(GlobalCRM.CurrentCaseID, CType(sender, Button).Tag) Then
            If (CType(sender, Button).Content.ToString().ToUpper() = "CONSULTATION COMPLETED") Then
                ' UPDATE THE case consultant id to the current con id

                Dim sqlquery As String
                sqlquery = "update D_Case set Case_ConCWID ='" & singleObject.CurrentConId & "' where Case_ID = '" & GlobalCRM.CurrentCaseID & "'"
                Dim result As Boolean = CommonDataFunctions.ExecuteSQL(sqlquery)
                If (result = False) Then
                    MsgBox("Cannot set " & singleObject.CurrentConName & " as the consultant of the case number : " & GlobalCRM.CurrentCaseID, MsgBoxStyle.Exclamation, "Error")
                End If
            End If
            If GblFunc_Populate_CaseStages(GlobalCRM.CurrentCaseID) Then
                'Dim myStage As Cases.CaseStage = Cases.GetCaseStage(GlobalCRM.CurrentCaseID)

                'If Not IsNothing(myStage) Then
                '    Me.lblCaseStatus.Text = myStage.StageTitle
                '    Me.lblDateStatus.Text = Format(myStage.StageDateSet, "dd-MMM-yyyy")
                'End If
                Me.DisplayNewCaseStatus(True)
                If GlobalCRM.CurrentCompanyID > 0 Then
                    Me.grdCases.ItemsSource = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(Me.CurrentCaseView, CaseTypes.Company))
                Else
                    Me.grdCases.ItemsSource = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(Me.CurrentCaseView, CaseTypes.Candidate))
                End If
            End If
            Dim caseStageTo As Integer = Cases.GetCaseStage(GlobalCRM.CurrentCaseID).StageNumber
            Admin.BookTheRelevantTask(caseStageFrom, caseStageTo)
            CommonFuncs.CommitTrans()
        End If
        loadTabEvent = False
        'ToolTip1.SetToolTip(Me.btnStage1, Me.btnStage1.Text)
        'ToolTip1.SetToolTip(Me.btnStage2, Me.btnStage2.Text)
        'ToolTip1.SetToolTip(Me.btnStage3, Me.btnStage3.Text)
        'ToolTip1.SetToolTip(Me.btnStage4, Me.btnStage4.Text)
        'ToolTip1.SetToolTip(Me.btnStage5, Me.btnStage5.Text)
        'ToolTip1.SetToolTip(Me.btnStage6, Me.btnStage6.Text)
    End Sub


    Private Sub AddHandlers()

        AddHandler grdCases.SelectionChanged, AddressOf grdCases_SelectedRowsChanged

        AddHandler radCaseAll.Checked, AddressOf CaseViewChanged
        AddHandler radCaseClosed.Checked, AddressOf CaseViewChanged
        AddHandler radCaseInit.Checked, AddressOf CaseViewChanged
        AddHandler radCaseOpen.Checked, AddressOf CaseViewChanged
        AddHandler radCasePreSale.Checked, AddressOf CaseViewChanged

        AddHandler radEventAll.Checked, AddressOf EventViewChanged
        AddHandler radEventCase.Checked, AddressOf EventViewChanged
        AddHandler radEventCombined.Checked, AddressOf EventViewChanged
        AddHandler radEventCompany.Checked, AddressOf EventViewChanged
        AddHandler radEventConsultant.Checked, AddressOf EventViewChanged
        AddHandler radEventPerson.Checked, AddressOf EventViewChanged

    End Sub

    Private Sub CaseViewChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles radCaseAll.CheckedChanged, radCaseClosed.CheckedChanged, radCaseInit.CheckedChanged, radCaseOpen.CheckedChanged, radCasePreSale.CheckedChanged

        RemoveHandler grdCases.SelectionChanged, AddressOf grdCases_SelectedRowsChanged

        If GlobalCRM.CurrentCompanyID > 0 Then
            Me.grdCases.ItemsSource = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(Me.CurrentCaseView, CaseTypes.Company))
        Else
            Me.grdCases.ItemsSource = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(Me.CurrentCaseView, CaseTypes.Candidate))
        End If

        AddHandler grdCases.SelectionChanged, AddressOf grdCases_SelectedRowsChanged

        'Me.SelectActiveCase()

    End Sub

    Private Function CurrentCaseView() As ViewByStatus

        If Me.radCaseAll.IsChecked Then
            Return ViewByStatus.AllCases
        ElseIf Me.radCaseClosed.IsChecked Then
            Return ViewByStatus.Closed
        ElseIf Me.radCaseInit.IsChecked Then
            Return ViewByStatus.Initiated
        ElseIf Me.radCaseOpen.IsChecked Then
            Return ViewByStatus.AllOpen
        ElseIf Me.radCasePreSale.IsChecked Then
            Return ViewByStatus.PreSale
        End If

    End Function

    Private Sub drpRoles_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles drpRoles.SelectionChanged
        'Dim sqlList As String = CommonDataFunctions.GetCorporatePeople(GlobalCRM.CurrentCompanyID, CommonDataFunctions.CompanyPeopleView.Category, CType(Me.drpRoles.SelectedValue, CommonDataFunctions.CompanyRoles))
        Dim corporatePeople As System.Data.DataTable = Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.Category, CType(Me.drpRoles.SelectedValue, Company.CompanyRoles))
        DataBinding.BindListView(corporatePeople, Me.lvwPeopleList)
        'DataBinding.BindListView(CommonSQL.GetCorporatePeople(GlobalCRM.CurrentCompanyID, CommonSQL.CompanyPeopleView.Category, CType(Me.drpRoles.SelectedValue, CommonSQL.CompanyRoles)), Me.lvwPeopleList)

    End Sub

    Private Sub drpEventView_SelectionChnaged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpEventView.SelectionChanged
        Me.Cursor = Cursors.Wait
        Me.RefreshEventList()
        Me.Cursor = Cursors.Arrow

    End Sub

    Public Sub RefreshEventList()

        If Me.radEventCase.IsChecked Then
            Me.EventSQL(EventView.CaseId, Me.drpEventView.SelectedValue)
            Me.lblViewingEvent.Content = "Viewing Events for: Case no. " & Me.drpEventView.Text  ' & " (" & Me.Combo_Events_DataToView.Column(1) & ")"
        ElseIf Me.radEventPerson.IsChecked Then
            Me.EventSQL(EventView.Person, Me.drpEventView.SelectedValue)
            Me.lblViewingEvent.Content = "Viewing Events for: Person no. " & Me.drpEventView.SelectedValue & " (" & Me.drpEventView.Text & ")"
        ElseIf Me.radEventConsultant.IsChecked Then
            Me.EventSQL(EventView.Consultant, Me.drpEventView.SelectedValue)
            Me.lblViewingEvent.Content = "Viewing Events for: Consultant no. " & Me.drpEventView.SelectedValue & " (" & Me.drpEventView.Text & ")"
        ElseIf Me.radEventAll.IsChecked Then
            ' - Testers wanted the defaulting for ALL. hence changed the defaulting as All.
            'It was combined before
            Me.EventSQL(EventView.All, GlobalCRM.CurrentCompanyID)
            'Me.EventSQL(EventView.All, Me.drpEventView.SelectedValue)
            Me.lblViewingEvent.Content = "Viewing Events for: Case no. " & Me.drpEventView.Text  ' & " (" & Me.Combo_Events_DataToView.Column(1) & ")"
        End If

        'DataBinding.BindListView(CommonSQL.GetEventsSQL(Me.drpEventView.SelectedValue, GlobalCRM.CurrentConID, tasksevents.EventTypes.EventCase), Me.lvwEvents)

        Me.lblMessage.Text = String.Empty

    End Sub

    Private Function EventSQL(ByVal EventType As EventView, ByVal LinkID As Long)


        Dim SQL As StringBuilder
        Dim LngContactID As Long, LngCandidateID As Long

        Select Case EventType

            Case EventView.Company

                'Get list of employees in company
                Dim Employees() As Long = Company.EmployeeList(LinkID)
                Dim i As Integer
                Dim EmployeeList As New StringBuilder

                If IsNothing(Employees) Then
                    Return String.Empty
                End If

                For i = Employees.GetLowerBound(0) To Employees.GetUpperBound(0)
                    EmployeeList.Append(Employees(i))
                    If i < Employees.GetUpperBound(0) Then
                        EmployeeList.Append(",")
                    End If
                Next

                SQL = New StringBuilder

                With SQL
                    .Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.con_name,")
                    .Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, ")
                    .Append(" Case Event_LinkType when 3 then 'Company' ")
                    .Append(" when 2 then D_Person.Person_Fname + ' ' + D_Person.Person_Lname")
                    .Append(" else 'Case' End as LinkFor")

                    'From Clause
                    .Append(" FROM D_Event LEFT OUTER JOIN")
                    .Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")
                    .Append(" Left Outer Join D_Person on D_Event.Event_LinkID = D_Person.Person_ID")

                    'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                    .Append(" WHERE ((D_Event.Event_LinkType = 3) And (D_Event.Event_LinkID = " & LinkID & "))")
                    If EmployeeList.ToString <> "" Then
                        .Append(" OR ((Event_LinkType = 2) AND (Event_LinkID in (" & EmployeeList.ToString & ")))")
                    End If

                    'Order By
                    .Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")
                End With

                Dim eventSummary As System.Data.DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                DataBinding.BindListView(eventSummary, Me.lvwEvents)


            Case EventView.Person
                'By Person

                'Select clause
                SQL = New StringBuilder
                With SQL
                    .Append("SELECT     TOP 100 PERCENT Event_ID,  CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT, ")
                    .Append("     Event_Description, ISNULL(ConScheduled, ConEntered) AS con_name, CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")

                    'From Clause
                    .Append("    WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, 'Person' AS Linkfor")
                    .Append(" FROM   dbo.V_Events WHERE     (Event_LinkType = 2) AND (Event_LinkID = " & LinkID & ")")

                    'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                    .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")

                    'Order By
                    '.Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")

                End With
                Dim eventSummary As System.Data.DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                DataBinding.BindListView(eventSummary, Me.lvwEvents)
                'DataBinding.BindListView(SQL.ToString(), Me.lvwEvents)
                'Call GblFunc_Populate_List(StrSQL, "MainDisplay_Event_List", Form_Fm_MainDisplay.List_Events)

                'Me.Btn_Event_AddNew.Caption = "Add Event to Person"
                'Me.Btn_Event_AddNew.Enabled = True
                'Me.Lbl_Events_ViewingFor.Caption = "Viewing Events for: Person no. " & Me.Combo_Events_DataToView & " (" & Me.Combo_Events_DataToView.Column(1) & ")"

            Case EventView.CaseId
                'By Case

                'Select clause
                SQL = New StringBuilder
                With SQL
                    '.Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.con_name,")
                    '.Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, Case Event_LinkType When 1 then 'Case' when 2 then 'Person' when 3 then 'Company' end as LinkFor")

                    ''From Clause
                    '.Append(" FROM D_Event LEFT OUTER JOIN")
                    '.Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                    ''VB Code Defnition Where Clause (Item ID and Link Type defined above)
                    '.Append(" WHERE (D_Event.Event_LinkType = 1) And (D_Event.Event_LinkID = " & LinkID & ")")

                    ''Order By
                    '.Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")


                    .Append("SELECT TOP 100 PERCENT Event_ID,  CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT, ")
                    .Append("   Event_Description, ISNULL(ConScheduled, ConEntered) AS con_name, ")
                    .Append("     CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")
                    .Append("  WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, ")
                    .Append("  CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor")
                    .Append(" FROM  dbo.V_Events WHERE  (Event_LinkID = " & LinkID & ") AND (Event_LinkType = 1)")
                    .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")


                End With
                Dim eventSummary As System.Data.DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                DataBinding.BindListView(eventSummary, Me.lvwEvents)
                ' DataBinding.BindListView(.ToString, Me.lvwEvents)
                'Call GblFunc_Populate_List(StrSQL, "MainDisplay_Event_List", Form_Fm_MainDisplay.List_Events)

                'Me.Btn_Event_AddNew.Caption = "Add Event to Case"
                'Me.Btn_Event_AddNew.Enabled = True
                'Me.Lbl_Events_ViewingFor.Caption = "Viewing Events for: Case no. " & Me.Combo_Events_DataToView & " (" & Me.Combo_Events_DataToView.Column(1) & " : " & Me.Combo_Events_DataToView.Column(2) & ")"

            Case EventView.Consultant

                Dim myData As System.Data.DataTable
                Dim myRow As DataRow
                Dim CaseList As New StringBuilder
                Dim PersonList As New StringBuilder

                'Everything entered by selected consultant

                'Need to assemble a list of all the Person and Case ref numbers for this company.

                'Cases first
                SQL = New StringBuilder
                With SQL
                    If GlobalCRM.CurrentCompanyID > 0 Then
                        .Append("Select Case_ID from  D_Case where Case_CompanyID = " & GlobalCRM.CurrentCompanyID)
                    Else
                        .Append("Select Case_ID from  D_Case where Case_CandidateID = " & GlobalCRM.CurrentCandidateID)
                    End If

                    myData = CommonDataFunctions.GetSQLDatatable(.ToString)
                End With

                For Each myRow In myData.Rows
                    CaseList.Append(myRow.Item("case_ID") & ",")
                Next

                myData.Dispose()

                'Now people
                'If Me.Page_Company.Visible = True Then
                SQL = New StringBuilder
                SQL.Append("Select Person_ID from  D_Person where Person_CompanyID = " & GlobalCRM.CurrentCompanyID) ' & Me.Txt_Company_ID)
                myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                For Each myRow In myData.Rows


                    PersonList.Append(myRow.Item("Person_ID") & ",")

                Next
                'Else
                'Rst.Close()
                'End If
                'Else
                'StrPersonList = Me.List_Person_People
                'End If

                'Now build the query for the event list (combo not needed for everything)

                'Select clause
                SQL = New StringBuilder
                With SQL
                    .Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.con_name,")
                    .Append("CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, Case Event_LinkType When 1 then 'Case' when 2 then 'Person' when 3 then 'Company' end as LinkFor ")

                    'From Clause
                    .Append("FROM D_Event LEFT OUTER JOIN")
                    .Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                    'VB Code Defnition Where Clause (Item ID and Link Type defined above)

                    If GlobalCRM.CurrentCompanyID > 0 Then
                        .Append(" WHERE ( (D_EVent.Event_linktype =  3 AND D_Event.Event_LinkID = " & LinkID & ")")

                        If PersonList.ToString <> "" Then
                            PersonList = New StringBuilder("(" & Strings.Left(PersonList.ToString, Len(PersonList.ToString) - 1) & ")")
                            .Append(" OR (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID in " & PersonList.ToString & ")")
                        End If

                    Else
                        .Append(" WHERE ( (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID = " & LinkID & ")")
                    End If

                    If CaseList.ToString <> "" Then
                        CaseList = New StringBuilder("(" & Strings.Left(CaseList.ToString, Len(CaseList.ToString) - 1) & ")")
                        .Append(" OR (D_EVent.Event_linktype =  1 AND D_Event.Event_LinkID in " & CaseList.ToString & ")")
                    End If

                    .Append(") AND Event_EnteredBy = " & LinkID)

                    'Order By
                    .Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")

                End With
                Dim eventSummary As System.Data.DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                DataBinding.BindListView(eventSummary, Me.lvwEvents)

                'DataBinding.BindListView(.ToString, Me.lvwEvents)
                'Me.Btn_Event_AddNew.Caption = "Add Event"
                'Me.Btn_Event_AddNew.Enabled = False
                'Me.Lbl_Events_ViewingFor.Caption = "Viewing Events for: All cases where entered by " & Me.Combo_Events_DataToView.Column(1)

            Case EventView.Combined
                'Case combined. All Events for selected case, plus those for the company (if present), candidate and contact (if present)

                Dim myData As System.Data.DataTable

                'Get candidate ID
                SQL = New StringBuilder

                SQL.Append("Select Case_CandidateID, Case_ContactID from D_Case where Case_ID = " & LinkID)
                myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                If myData.Rows.Count > 0 Then


                    LngCandidateID = myData.Rows(0).Item("Case_CandidateID")
                    LngContactID = myData.Rows(0).Item("Case_ContactID")
                End If
                myData.Dispose()


                'Select clause
                SQL = New StringBuilder
                With SQL
                    .Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.con_name,")
                    .Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category,")

                    If GlobalCRM.CurrentCompanyID > 0 Then
                        .Append(" Case  ")
                        .Append("When Event_LinkType = 1 then 'Case' ")
                        .Append(" when Event_LinkType = 2 and Event_LinkID = " & LngCandidateID & " then 'Candidate' ")
                        .Append(" when Event_LinkType = 2 and Event_LinkID = " & LngContactID & " then 'Contact' ")
                        .Append(" when Event_LinkType = 2 then 'Person' ")
                        .Append("when Event_LinkType = 3 then 'Company' end as LinkFor")
                    Else
                        .Append(" Case  ")
                        .Append(" When Event_LinkType = 1 then 'Case' ")
                        .Append(" when Event_LinkType = 2 then 'Client' end as LinkFor")
                    End If

                    'From Clause
                    .Append(" FROM D_Event LEFT OUTER JOIN")
                    .Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                    'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                    .Append(" WHERE (D_Event.Event_LinkType = 1) And (D_Event.Event_LinkID = " & LinkID & ")")

                    'Also get candidate events if candidate ID known
                    If LngCandidateID <> 0 Then
                        .Append(" OR (D_Event.Event_LinkType = 2) And (D_Event.Event_LinkID = " & LngCandidateID & ")")
                    End If

                    'is this a company case
                    If GlobalCRM.CurrentCompanyID > 0 Then

                        'Get company events as well
                        .Append(" OR (D_Event.Event_LinkType = 3) And (D_Event.Event_LinkID = " & GlobalCRM.CurrentCompanyID & ")")

                        'if we have a contact, get thier events as well
                        If LngContactID <> 0 Then
                            .Append(" OR (D_Event.Event_LinkType = 2) And (D_Event.Event_LinkID = " & LngContactID & ")")
                        End If
                    End If


                    'Order By
                    .Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")

                End With
                Dim eventSummary As System.Data.DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                DataBinding.BindListView(eventSummary, Me.lvwEvents)
                'DataBinding.BindListView(.ToString, Me.lvwEvents)

            Case EventView.All

                Dim CaseList() As Long = Nothing
                Dim myData As System.Data.DataTable
                Dim myRow As DataRow
                Dim i As Integer

                If GlobalCRM.CurrentCompanyID > 0 Then
                    'Need to assemble a list of all the Person and Case ref numbers for this company.

                    'Cases first

                    Dim PeopleList() As Long = Nothing

                    SQL = New StringBuilder
                    SQL.Append("Select Case_ID from D_Case where Case_CompanyID = " & GlobalCRM.CurrentCompanyID)

                    myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                    If IsNothing(myData) Then
                        Exit Function
                    End If

                    For Each myRow In myData.Rows
                        ReDim Preserve CaseList(i)
                        CaseList(i) = myRow.Item("case_id")
                        i = i + 1 'Harvey added this to fix problem
                    Next

                    myData.Dispose()

                    'Now people
                    SQL = New StringBuilder
                    SQL.Append("Select Person_ID from  D_Person where Person_CompanyID = " & GlobalCRM.CurrentCompanyID)

                    myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                    If IsNothing(myData) Then
                        Exit Function
                    End If

                    i = 0

                    For Each myRow In myData.Rows
                        ReDim Preserve PeopleList(i)
                        PeopleList(i) = myRow.Item("person_id")
                        i = i + 1 'Harvey added this to fix problem
                    Next

                    myData.Dispose()

                    'Now build the query for the event list (combo not needed for everything)

                    'Select clause
                    SQL = New StringBuilder
                    With SQL
                        '.Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.con_name,")
                        '.Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, Case Event_LinkType When 1 then 'Case' when 2 then 'Person' when 3 then 'Company' end as LinkFor")

                        ''From Clause
                        '.Append(" FROM D_Event LEFT OUTER JOIN")
                        '.Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                        ''VB Code Defnition Where Clause (Item ID and Link Type defined above)
                        '.Append(" WHERE (D_EVent.Event_linktype =  3 AND D_Event.Event_LinkID = " & GlobalCRM.CurrentCompanyID & ")")
                        'If Not CaseList Is Nothing Then
                        '    If CaseList.Length > 0 Then
                        '        .Append(" OR (D_EVent.Event_linktype =  1 AND D_Event.Event_LinkID in " & CommonFunc.ArrayToCSV(CaseList) & ")")
                        '    End If
                        'End If
                        'If Not PeopleList Is Nothing Then
                        '    If PeopleList.Length > 0 Then
                        '        .Append(" OR (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID in " & CommonFunc.ArrayToCSV(PeopleList) & ")")
                        '    End If
                        'End If
                        ''Order By
                        '.Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")


                        .Append("SELECT     TOP 100 PERCENT Event_ID,  CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT, ")
                        .Append(" Event_Description, ISNULL(ConScheduled, ConEntered) AS con_name,  CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")
                        .Append(" WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category,  CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor")


                        'From Clause
                        .Append(" FROM         dbo.V_Events")

                        'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                        .Append(" WHERE (Event_linktype =  3 AND Event_LinkID = " & GlobalCRM.CurrentCompanyID & ")")
                        If Not CaseList Is Nothing Then
                            If CaseList.Length > 0 Then
                                .Append(" OR (Event_linktype =  1 AND Event_LinkID in " & CRM.BusinessLayer.CommonFuncs.ArrayToCSV(CaseList) & ")")
                            End If
                        End If
                        If Not PeopleList Is Nothing Then
                            If PeopleList.Length > 0 Then
                                .Append(" OR (Event_linktype =  2 AND Event_LinkID in " & CRM.BusinessLayer.CommonFuncs.ArrayToCSV(PeopleList) & ")")
                            End If
                        End If
                        'Order By
                        .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")

                    End With



                Else
                    'Private individual

                    'Only need to assemble case list
                    'Cases first
                    SQL = New StringBuilder
                    SQL.Append("Select Case_ID from D_Case where Case_CandidateID = " & ActivePersonId)

                    myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

                    If IsNothing(myData) Then
                        Exit Function
                    End If

                    For Each myRow In myData.Rows
                        ReDim Preserve CaseList(i)
                        CaseList(i) = myRow.Item("case_id")
                        i = i + 1 'Harvey added this to fix problem
                    Next

                    myData.Dispose()

                    'Now build the query for the event list (combo not needed for everything)

                    'Select clause
                    SQL = New StringBuilder

                    With SQL
                        '.Append("SELECT D_Event.Event_ID, Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end as EventDT, D_Event.Event_Description, L_Consultant.con_name,")
                        '.Append(" CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + convert(varchar(12),Event_DTScheduled,103) WHEN 3 THEN 'Completed on ' + convert(varchar(12),Event_DTCompleted,103) END AS Category, Case Event_LinkType When 1 then 'Case' when 2 then 'Person' when 3 then 'Company' end as LinkFor")

                        ''From Clause
                        '.Append(" FROM D_Event LEFT OUTER JOIN")
                        '.Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                        ''VB Code Defnition Where Clause (Item ID and Link Type defined above)
                        '.Append(" WHERE (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID = " & Me.ActivePersonId & ")")

                        'If CaseList.Length > 0 Then
                        '    .Append(" OR (D_EVent.Event_linktype =  1 AND D_Event.Event_LinkID in " & CommonFunc.ArrayToCSV(CaseList) & ")")
                        'End If

                        ''Order By
                        '.Append(" Order By Case Event_Category When 2 then Event_Dtscheduled when 3 then Event_Dtcompleted else Event_Dtentered end Desc")


                        .Append("SELECT TOP 100 PERCENT Event_ID, CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT,Event_Description ")
                        .Append(" , ISNULL(ConScheduled, ConEntered) AS con_name,  CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")

                        'From Clause
                        .Append(" WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor FROM dbo.V_Events WHERE (Event_LinkType = 2) AND (Event_LinkID = " & Me.ActivePersonId & ")")
                        '.Append(" L_Consultant ON D_Event.Event_Enteredby = L_Consultant.Con_ID")

                        'VB Code Defnition Where Clause (Item ID and Link Type defined above)
                        ' .Append(" WHERE (D_EVent.Event_linktype =  2 AND D_Event.Event_LinkID = " & Me.ActivePersonId & ")")

                        If CaseList.Length > 0 Then
                            .Append(" OR (Event_LinkType = 1) AND (Event_LinkID IN " & CRM.BusinessLayer.CommonFuncs.ArrayToCSV(CaseList) & ")")
                        End If

                        'Order By
                        .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")



                        '.Append("SELECT TOP 100 PERCENT Event_ID, CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT,Event_Description ")
                        '.Append(", ISNULL(ConScheduled, ConEntered) AS con_name,  CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")
                        '.Append("  WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor FROM dbo.V_Events WHERE (Event_LinkType = 2) AND (Event_LinkID = " & Me.ActivePersonId & ") OR (Event_LinkType = 1) AND (Event_LinkID IN " & CommonFunc.ArrayToCSV(CaseList) & ")")
                        '.Append("  ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")
                        '.Append(" FROM dbo.V_Events WHERE   (Event_LinkType = 2) AND (Event_LinkID = " & Me.ActivePersonId & ") OR  (Event_LinkType = 1) AND (Event_LinkID IN " & CommonFunc.ArrayToCSV(CaseList) & ")")
                        '.Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")

                    End With


                End If
                Dim eventSummary As System.Data.DataTable
                eventSummary = CommonDataFunctions.GetSQLDatatable(SQL.ToString())
                DataBinding.BindListView(eventSummary, Me.lvwEvents)

                'DataBinding.BindListView(SQL.ToString, Me.lvwEvents)



                'Me.Btn_Event_AddNew.Caption = "Add Event to Case"
                'Me.Btn_Event_AddNew.Enabled = True
                'Me.Lbl_Events_ViewingFor.Caption = "Viewing Events for: Case no. " & Me.Combo_Events_DataToView & " (" & Me.Combo_Events_DataToView.Column(1) & " : " & Me.Combo_Events_DataToView.Column(2) & ")"

        End Select

        'Set up query for Event Dump
        'If StrSQL <> "" Then
        '    StrSQL = Right(StrSQL, Len(StrSQL) - 6)

        '    StrSQL = "Select Event_Message, " & StrSQL
        '    Call GblFunc_Create_Query(StrSQL, "Qry_SQL_Rpt_Maindisplay_EventDump")
        'End If

        Exit Function


    End Function

    Private Sub EventViewChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles radEventAll.CheckedChanged, radEventCase.CheckedChanged, radEventCombined.CheckedChanged, radEventCompany.CheckedChanged, radEventConsultant.CheckedChanged, radEventPerson.CheckedChanged

        RemoveHandler drpEventView.SelectionChanged, AddressOf drpEventView_SelectionChnaged

        'Me.lvwEvents.Items.Clear()

        'Select Case CType(CType(sender, RadioButton).Tag, EventView)

        ' if Case or Combined selected
        If radEventCase.IsChecked = True Or radEventCombined.IsChecked Then '    Case EventView.CaseId, EventView.Combined
            Me.btnAddEventToCase.IsEnabled = True

            Me.lblEventView.Content = "View Case"
            Me.btnAddEventToCase.Content = "Add Event to Case"
            Me.lblViewingEvent.Content = "Viewing Events for: Case not selected"

            If GlobalCRM.CurrentCompanyID > 0 Then

                With Me.drpEventView
                    .IsEnabled = True
                    .ItemsSource = Nothing
                    .DisplayMemberPath = "display_member"
                    .SelectedValuePath = "Case_ID"
                    .ItemsSource = CType(Company.CompanyCases(GlobalCRM.CurrentCompanyID), IListSource).GetList
                    .SelectedIndex = -1
                End With
            Else

                With Me.drpEventView
                    .IsEnabled = True
                    .ItemsSource = Nothing
                    .DisplayMemberPath = "displayname"
                    .SelectedValuePath = "case_id"
                    .ItemsSource = CType(Cases.GetCaseList(GlobalCRM.CurrentCandidateID), IListSource).GetList

                    If .Items.Count > 0 Then
                        .SelectedIndex = 0
                    End If
                End With

            End If

            If Me.drpEventView.Items.Count > 0 Then
                Me.drpEventView.SelectedIndex = 0
                drpEventView_SelectionChnaged(Nothing, New System.EventArgs)

            Else
                Me.drpEventView.SelectedIndex = -1
            End If


            'Me.EventSQL(EventView.CaseId, GlobalCRM.CurrentCaseID)
            'Case EventView.Combined
            'Me.EventSQL(EventView.Combined)

            ' if All selected
        ElseIf radEventAll.IsChecked = True Then
            '            Case EventView.All
            Me.lblEventView.Content = String.Empty
            Me.btnAddEventToCase.IsEnabled = False
            Me.drpEventView.IsEnabled = False
            Me.drpEventView.ItemsSource = Nothing
            If GlobalCRM.CurrentCompanyID > 0 Then
                Me.EventSQL(EventView.All, GlobalCRM.CurrentCompanyID)
            Else

                Me.EventSQL(EventView.All, GlobalCRM.CurrentCaseID)
            End If
            ' if Company selected
            '           Case EventView.Company
        ElseIf radEventCompany.IsChecked = True Then
            Me.btnAddEventToCase.IsEnabled = False
            Me.lblEventView.Content = String.Empty
            Me.drpEventView.IsEnabled = False
            Me.drpEventView.ItemsSource = Nothing
            If GlobalCRM.CurrentCompanyID > 0 Then
                Me.EventSQL(EventView.Company, GlobalCRM.CurrentCompanyID)
            End If
            Me.lblViewingEvent.Content = "Viewing Events for: Company and Contacts"

            ' if Consultant selected
            'Case EventView.Consultant
        ElseIf radEventConsultant.IsChecked = True Then
            'Me.EventSQL(EventView.Consultant, GlobalCRM.CurrentConID)
            Me.lblEventView.Content = "View Consultant"
            Me.btnAddEventToCase.IsEnabled = False
            Me.lblViewingEvent.Content = "Viewing Events for: Consultant not selected"

            With Me.drpEventView
                .IsEnabled = True
                .ItemsSource = Nothing
                .DisplayMemberPath = "con_name"
                .SelectedValuePath = "con_id"
                .ItemsSource = CType(CommonDataFunctions.ConsultantList(True), IListSource).GetList
                .SelectedIndex = -1
            End With

            ' if Person selected
            'Case EventView.Person
        ElseIf radEventPerson.IsChecked = True Then

            Me.btnAddEventToCase.IsEnabled = True
            Me.lblEventView.Content = "View Person"
            Me.btnAddEventToCase.Content = "Add Event to Person"
            Me.lblViewingEvent.Content = "Viewing Events for: Person not selected"

            If GlobalCRM.CurrentCompanyID > 0 Then

                With Me.drpEventView
                    .IsEnabled = True
                    .ItemsSource = Nothing
                    .DisplayMemberPath = "person_name"
                    .SelectedValuePath = "Person_ID"
                    .ItemsSource = CType(Company.CompanyPeople(GlobalCRM.CurrentCompanyID), IListSource).GetList
                    .SelectedIndex = -1
                End With
            Else
                With Me.drpEventView

                    ' xxx continue here - add Person's name to the drop down list

                    Dim myTable As New System.Data.DataTable
                    .DisplayMemberPath = "PersonFullName"
                    .SelectedValuePath = "Person_ID"
                    myTable = CommonDataFunctions.GetSQLDatatable("Select Person_ID, Person_Fname + ' ' + Person_LName as PersonFullName From D_Person Where Person_ID = " & GlobalCRM.CurrentCandidateID)
                    .ItemsSource = CType(myTable, IListSource).GetList
                    .SelectedIndex = 0
                    .IsEnabled = False

                    'Dim myItem As New DataBinding.MyListItem
                    '.DataSource = Nothing
                    'myItem.ItemText = GlobalCRM.CurrentCandidateName.ToString
                    'myItem.ItemValue = GlobalCRM.CurrentCandidateID
                    '.Items.Add(myItem)
                    '.DisplayMember = "itemtext"
                    '.ValueMember = "itemvalue"
                    '.SelectedIndex = 0
                    'Me.drpEventView.Enabled = False

                    'Dim ci As Xceed.Editors.ComboBoxItem


                    ' Me.WinComboBox1.Items.Add(Xceed.Editors.ComboBoxItem("h", "1"))

                    '.Enabled = True
                    '.DataSource = Nothing
                    '.DisplayMember = "displayname"
                    '.ValueMember = "case_id"
                    '.DataSource = Cases.GetCaseList(GlobalCRM.CurrentCandidateID)

                    'If .Items.Count > 0 Then
                    '    .SelectedIndex = 0
                    'End If
                End With

                DataBinding.BindListView(People.GetPersonEvents(GlobalCRM.CurrentCandidateID), lvwEvents)

            End If


            'Me.EventSQL(EventView.Person, GlobalCRM.CurrentCandidateID)


        End If

        AddHandler drpEventView.SelectionChanged, AddressOf drpEventView_SelectionChnaged

    End Sub

    Private Function CaseListSQL(ByVal CaseView As ViewByStatus, ByVal CaseType As CaseTypes) As String

        Dim SQL As New StringBuilder

        With SQL
            .Append("SELECT D_Case.Case_ID as CaseID, Case Case_ActiveStatus when 1 then 'ON HOLD: ' else '' end + L_CaseStages.CaseStage_Title as Status,")
            '.Append("SELECT D_Case.Case_ID, Case Case_ActiveStatus when 1 then 'ON HOLD: ' else '' end + L_CaseStages.CaseStage_Title as CaseStage,")
            .Append("L_Products.Product_Name as Product, L_Consultant_Sales.con_name AS Consultant, L_Consultant_Case.con_name AS Caseworker, L_Consultant_Coordinator.con_name as Coordinator, ")
            .Append(" dbo.V_CaseWithPeople.Candidate as Candidate, ")
            '.Append("L_Products.Product_Name, L_Consultant_Sales.con_name AS Consultant, L_Consultant_Case.con_name AS Caseworker,")
            .Append("V_CaseWithPeople.Contact as Contact , CONVERT(VARCHAR(10),")
            .Append("D_Case.Case_DTStatus, 103) AS DateStatus FROM V_CaseWithPeople RIGHT OUTER JOIN D_Case ON V_CaseWithPeople.Case_ID = D_Case.Case_ID ")
            .Append("LEFT OUTER JOIN L_Consultant L_Consultant_Case ON D_Case.Case_ConCWID = L_Consultant_Case.Con_ID LEFT OUTER JOIN L_Consultant L_Consultant_Sales ON ")
            .Append("D_Case.Case_ConSaleID = L_Consultant_Sales.Con_ID LEFT OUTER JOIN L_CaseStages ON D_Case.Case_StatusID = L_CaseStages.CaseStage_Number LEFT OUTER JOIN L_Products ON D_Case.Case_ProductID = L_Products.Product_ID ")
            .Append("Left outer join L_Consultant L_Consultant_Coordinator on D_Case.Case_CoordinatorID = L_Consultant_Coordinator.Con_Id ")
            '.Append("Left join V_CaseContact on D_Case.Case_ID = V_CaseContact.Case_ID ")
            Select Case CaseView
                Case ViewByStatus.AllOpen
                    .Append("WHERE (D_Case.Case_StatusID < 1000) And ")
                Case ViewByStatus.AllCases
                    .Append("WHERE ")
                Case ViewByStatus.Closed
                    .Append("WHERE (D_Case.Case_StatusID >= 1000) And ")
                Case ViewByStatus.PreSale
                    .Append("WHERE (D_Case.Case_StatusID < 100) And ")
                Case ViewByStatus.Initiated
                    .Append("WHERE (D_Case.Case_StatusID between 100 and 999) And ")

            End Select
            Select Case CaseType
                Case CaseTypes.Candidate
                    .Append("(D_Case.Case_CandidateID = " & GlobalCRM.CurrentCandidateID & ") ")
                Case CaseTypes.Company
                    .Append("(D_Case.Case_companyID = " & GlobalCRM.CurrentCompanyID & ") ")

            End Select

            .Append("Order By D_Case.Case_ID Desc")
            Return .ToString
        End With

    End Function

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClose.Click
        'Cases.UnLockCase(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentConID)
        'Me.Close()
        'Dim MDI As New frmCRMMDI
        'MDI.LoadFrontPage()
        'Me.Close()
        RaiseEvent CloseDynamicTab("maindisplay")
    End Sub

    Private Sub RemoveHandlers()
        RemoveHandler grdCases.SelectionChanged, AddressOf grdCases_SelectedRowsChanged
    End Sub

    Private Sub grdCases_SelectedRowsChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles grdCases.SelectedRowsChanged
        Dim blnRefresh As Boolean = False
        'The selected case has change, update accordingly
        If Not grdCases.SelectedItem Is Nothing Then
            If grdCases.SelectedItem.itemarray(0) <> GlobalCRM.CurrentCaseID Then
                rowselectionchanged = False
            End If
        Else
            blnRefresh = True
            rowselectionchanged = True
        End If
        If rowselectionchanged = False Then
            rowselectionchanged = True
            Me.SelectedCaseChanged()
        ElseIf blnRefresh = True Then
            blnRefresh = False
            Me.SelectedCaseChanged()
        End If
    End Sub

    Private Sub SelectedCaseChanged()

        Dim objCase As Cases.CaseInfo

        Try
            loadTabDocs = False
            If Me.grdCases.SelectedItems.Count > 0 Or GlobalCRM.CurrentCompanyID > 0 Or GlobalCRM.CurrentCaseID > 0 Then

                'Dim myStage As Cases.CaseStage
                Dim myDocSummary As CommonDataFunctions.DocumentsSummary
                Dim myAccountsSummary As Accounts.AccountsSummary
                Dim myCorpContact As Company.CorporateContact = Nothing

                Dim currentRow As DataRow = grdCases.SelectedItem
                If Not currentRow Is Nothing Then

                    GlobalCRM.CurrentCaseID = currentRow(0)
                Else
                    ' If GlobalCRM.CurrentCompanyID = 0 Then
                    Dim drow As System.Data.DataTable = grdCases.ItemsSource

                    GlobalCRM.CurrentCaseID = drow.Rows(0)(0)
                    'End If
                End If

                myDocSummary = CommonDataFunctions.GetDocStoreSummary(GlobalCRM.CurrentCaseID)
                myAccountsSummary = Accounts.GetAccountsSummary(GlobalCRM.CurrentCaseID)



                If GlobalCRM.CurrentCompanyID > 0 Then
                    myCorpContact = Company.GetCorporateContact(GlobalCRM.CurrentCaseID)
                End If
                Me.DisplayNewCaseStatus()

                If Not IsNothing(myDocSummary) Then
                    With myDocSummary
                        Me.lblNoDocOut.Content = .Required - .Received
                        Me.lblNoDocReq.Content = .Required
                        Me.lblNoDocStore.Content = .InDocStore
                    End With
                End If

                DisplayAccountsSummary(myAccountsSummary)

                Me.lblCandidateName2.Content = GlobalCRM.CurrentCandidateName
                Me.lblCandidateID2.Content = GlobalCRM.CurrentCandidateID

                If Not IsNothing(myCorpContact) Then
                    Me.lblContactName.Content = myCorpContact.ContactName
                    Me.lblContactId.Content = myCorpContact.ContactID
                End If

                GblFunc_Populate_CaseStages(GlobalCRM.CurrentCaseID)
                'Me.LoadEventsTab()
                'Me.LoadKeyDatesTab()
                Me.GblFunc_Populate_MFB(GlobalCRM.CurrentCaseID)

                Dim myCase As Cases.CaseInfo = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID)

                Me.lblSubmitDate.Content = String.Empty

                If IsDate(myCase.SubmittedDate) Then
                    If myCase.SubmittedDate.Year > 1950 Then
                        Me.lblSubmitDate.Content = Format(myCase.SubmittedDate, "dd/MM/yyyy")
                    End If
                End If
                If IsDate(myCase.WrittenOffDate) Then
                    If myCase.WrittenOffDate.Year > 1950 Then
                        Me.lblWriteOffDate.Visibility = System.Windows.Visibility.Visible
                        Me.lblWrittenOff.Visibility = System.Windows.Visibility.Visible
                        Me.lblWriteOffDate.Content = Format(myCase.WrittenOffDate, "dd/MM/yyyy")
                    Else
                        Me.lblWriteOffDate.Visibility = System.Windows.Visibility.Hidden
                        Me.lblWrittenOff.Visibility = System.Windows.Visibility.Hidden
                        Me.lblWriteOffDate.Content = String.Empty
                    End If
                End If
                Me.lblDocReqDate.Content = DisplayDate(myCase.CriticalDate)
                Me.lblSubmitDate.Content = DisplayDate(myCase.SubmittedDate)
                Me.lblExtRef.Content = myCase.ExtRef
                Me.lblExpiry.Content = DisplayDate(myCase.ExpiryDate)
                Me.lblFTDate.Content = DisplayDate(myCase.FastTrackDate)


                Dim myParent As People.ParentInfo = People.GetParentPerson(GlobalCRM.CurrentCandidateID)

                If myParent.ParentId > 0 Then
                    Me.grpDependantOf.Visibility = System.Windows.Visibility.Visible
                    Me.lblDependOfName.Content = myParent.ParentName
                    Me.lblDependOfId.Content = myParent.ParentId
                Else
                    Me.lblDependOfName.Content = String.Empty
                    Me.lblDependOfId.Content = String.Empty
                    Me.grpDependantOf.Visibility = System.Windows.Visibility.Hidden
                End If

                Me.TabControl2.IsEnabled = True

                Me.btnEditCase.IsEnabled = True
                Me.btnSend.IsEnabled = True
                Me.btnInbox.IsEnabled = True
                Me.btnStockLetters.IsEnabled = True
                Me.btnAddCaseEvent.IsEnabled = True
                Me.btnViewCaseEvents.IsEnabled = True
                Me.btnAddCFF.IsEnabled = True
                Me.btnFileAudit.IsEnabled = True
                Me.btnCreditController.IsEnabled = True
                Me.btnRevertWriteOff.IsEnabled = True

                If CRM.BusinessLayer.CommonFuncs.WriteOffAccess(GlobalCRM.CurrentConID) = 1 And GetStatusFromCase(GlobalCRM.CurrentCaseID) <> 2000 Then
                    Me.btnCreditController.IsEnabled = True

                Else
                    Me.btnCreditController.IsEnabled = False
                    'Me.btnRevertWriteOff.Enabled = False
                    'Me.btnEmailEvents.Enabled = False
                End If
                If CommonFuncs.RevertWriteOffAccess(GlobalCRM.CurrentConID) = 1 And GetStatusFromCase(GlobalCRM.CurrentCaseID) = 2000 Then

                    Me.btnRevertWriteOff.IsEnabled = True
                    'Me.btnEmailEvents.Enabled = True
                Else

                    Me.btnRevertWriteOff.IsEnabled = False
                    'Me.btnEmailEvents.Enabled = False
                End If

            End If
            'check whether the case is with credit controller
            If GlobalCRM.CurrentCaseID > 0 Then
                If GlobalCRM.CreditControllerCaseID <> GlobalCRM.CurrentCaseID Then
                    If CRM.BusinessLayer.CommonFuncs.ISWithCreditController(GlobalCRM.CurrentCaseID) Then
                        'MsgBox("The case is with the credit controller. Please do not work with this case ", MsgBoxStyle.Critical, "CC")
                        'IDSearch = "The case search has been completed"
                        'lblCreditController.Visible = False
                        'Exit Sub
                        'MsgBox("Case is with credit controller. Please do not work on this case", MsgBoxStyle.Critical, "CreditController")
                        Dim frmMessageBox As New frmMessageBox()
                        frmMessageBox.ShowDialog()
                        'display message box - 
                        GlobalCRM.CreditControllerCaseID = GlobalCRM.CurrentCaseID
                        lblCreditController.Content = "Case with credit controller. Stop working on this case"
                        lblCreditController.Visibility = System.Windows.Visibility.Visible

                    Else
                        lblCreditController.Content = String.Empty
                        lblCreditController.Visibility = System.Windows.Visibility.Hidden
                        GlobalCRM.CreditControllerCaseID = GlobalCRM.CurrentCaseID
                    End If
                End If
                'If GlobalCRM.CurrentCaseID > 0 Then
                If GlobalCRM.WrittenOffCaseID <> GlobalCRM.CurrentCaseID Then
                    If CommonFuncs.ISCaseWrittenOff(GlobalCRM.CurrentCaseID) Then
                        Dim msgWriteBox As New frmMessageBoxWriteOff
                        msgWriteBox.ShowDialog()
                        'display message box - 
                        GlobalCRM.WrittenOffCaseID = GlobalCRM.CurrentCaseID
                        lblCreditController.Content = "Case has been written Off. Stop working on this case"
                        lblCreditController.Visibility = System.Windows.Visibility.Visible

                    Else
                        lblCreditController.Content = String.Empty
                        lblCreditController.Visibility = System.Windows.Visibility.Hidden
                        GlobalCRM.WrittenOffCaseID = GlobalCRM.CurrentCaseID
                    End If
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainDisplay.SelectedCaseChange")
        Finally
            objCase = Nothing
        End Try

    End Sub

    Private Function DisplayDate(ByVal dte As Date) As String
        If dte = DateSerial(1900, 1, 1) Or dte = TimeSerial(0, 0, 0) Then
            Return String.Empty
        Else
            Return dte.ToShortDateString
        End If
    End Function

    Public Function GblFunc_Populate_MFB(ByVal LngCaseID As Long) As Integer

        Dim IntGroup As Integer
        Dim IntAssSLS As Integer
        Dim SQL As New StringBuilder
        Dim myButton As Button
        'Dim DB As New CRM.DataLayer.DataAccess()

        Me.MFB1.Visibility = System.Windows.Visibility.Hidden
        Me.MFB2.Visibility = System.Windows.Visibility.Hidden
        Me.MFB3.Visibility = System.Windows.Visibility.Hidden
        Me.MFB4.Visibility = System.Windows.Visibility.Hidden
        Me.MFB5.Visibility = System.Windows.Visibility.Hidden
        Me.MFB6.Visibility = System.Windows.Visibility.Hidden
        Me.MFB7.Visibility = System.Windows.Visibility.Hidden
        Me.MFB8.Visibility = System.Windows.Visibility.Hidden
        Me.MFB9.Visibility = System.Windows.Visibility.Hidden

        If GlobalCRM.CurrentCaseID = 0 Then
            Exit Function
        End If

        'Before getting buttons, check for assessing auth SLS as if not present will need to diable certain buttons later

        Dim myData As System.Data.DataTable
        Dim myRow As DataRow

        With SQL
            .Append("SELECT L_AssessingAuths.Assessingauth_SLSID")
            .Append(" FROM D_Case INNER JOIN")
            .Append(" D_Person ON D_Case.Case_CandidateID = D_Person.Person_ID INNER JOIN")
            .Append(" L_SkilledOcc ON D_Person.Person_SkilledOccID = L_SkilledOcc.SkilledOcc_ID INNER JOIN")
            .Append(" L_AssessingAuths ON L_SkilledOcc.SkilledOcc_AuthID = L_AssessingAuths.AssessingAuth_ID")
            .Append(" WHERE (D_Case.Case_ID = " & GlobalCRM.CurrentCaseID & ")")
        End With

        If CommonDataFunctions.GetSQLScalar(SQL.ToString) <> 0 Then
            IntAssSLS = 1
        End If

        'Get the Group for this case
        IntGroup = CRM.BusinessLayer.CommonDataFunctions.GblFunc_Get_Dataset(GlobalCRM.CurrentCaseID, 2) 'mfb group

        If IntGroup = 0 Then
            'Nothing found, probably no product or product type, leave MFB blank
            Exit Function
        End If

        Dim myCase As Cases.CaseInfo = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID)

        'Now know the current stage and the group, so begin to populate

        'Get relevent entries based on group and current stage

        SQL = New StringBuilder

        With SQL
            .Append("SELECT I_MFB.MFB_ID, I_MFB.MFB_Title, I_MFBLinks.MFBLink_Position")
            .Append(" FROM I_MFB INNER JOIN I_MFBLinks ON I_MFB.MFB_ID = I_MFBLinks.MFBLink_MFBID")

            .Append(" WHERE (I_MFBLinks.MFBLink_GroupID = " & IntGroup & ") ")

            'Check for correct customer type
            If GlobalCRM.CurrentCompanyID = 0 Then
                'Individual
                .Append(" AND (I_MFBLInks.MFBLink_CustomerType = 0 Or I_MFBLInks.MFBLink_CustomerType = 1)")
            Else
                'Company
                .Append(" AND (I_MFBLInks.MFBLink_CustomerType = 0 Or I_MFBLInks.MFBLink_CustomerType = 2)")
            End If

            'Check System Version
            .Append(" AND (I_MFBLInks.MFBLink_SystemVersionActive  < = " & GlobalCRM.SysVersion & " )")
            .Append(" AND (I_MFBLInks.MFBLink_SystemVersionDisable > " & GlobalCRM.SysVersion & " OR I_MFBLinks.MFBLink_SystemVersionDisable = 0)")

            .Append(" AND (")
            .Append(" (I_MFBLinks.MFBLink_StageStart <= " & myCase.CaseStatusId & " AND I_MFBLinks.MFBLink_StageEnd > " & myCase.CaseStatusId & ")")
            .Append(" OR ")
            .Append(" (I_MFBLinks.MFBLink_StageStart = 0 AND I_MFBLinks.MFBLink_StageEnd > " & myCase.CaseStatusId & ")")
            .Append(" OR ")
            .Append(" (I_MFBLinks.MFBLink_StageStart <= " & myCase.CaseStatusId & " AND I_MFBLinks.MFBLink_StageEnd = 0)")
            .Append(" OR ")
            .Append(" (I_MFBLinks.MFBLink_StageStart = 0 AND I_MFBLinks.MFBLink_StageEnd = 0)")
            .Append(" )")
        End With

        myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

        If IsNothing(myData) Then
            'Error State
            CommonFuncs.DisplayMessage("Call failed when polling for buttons", CommonDialog.CustomDialogIcons.Information, " ")
            Exit Function
        End If

        If myData.Rows.Count = 0 Then
            myData.Dispose()
            'No buttons for this product/stage combo!
            Exit Function
        End If

        'Set the captions and make the buttons visible
        For Each myRow In myData.Rows

            For Each currentButton As FrameworkElement In grdTabCase.Children()
                If currentButton.GetType() Is GetType(System.Windows.Controls.Button) Then
                    If currentButton.Name = "MFB" & myRow.Item("MFBLink_Position") Then
                        myButton = currentButton
                    End If
                End If
            Next
            If myRow.Item("MFB_ID") = 8 Then
                If Not myCase.OnHold Then
                    myButton.Content = "Put case on hold"
                Else
                    myButton.Content = "Take case off hold"
                End If

            Else
                myButton.Content = myRow.Item("MFB_Title")
            End If

            If myRow.Item("MFB_ID") = 7 Then
                'Assessing auth SLS button, only switch on if there is an SLS available for this case
                If IntAssSLS = 1 Then
                    myButton.Visibility = System.Windows.Visibility.Visible
                End If
            Else
                myButton.Visibility = System.Windows.Visibility.Visible
            End If


        Next

        myData.Dispose()

    End Function

    Private Sub LoadEventsTab()
        Dim itemTable As System.Data.DataTable
        itemTable = CRM.BusinessLayer.Cases.GetCaseEvents(CRM.BusinessLayer.GlobalCRM.CurrentCaseID, CRM.BusinessLayer.GlobalCRM.CurrentCandidateID)
        DataBinding.BindListView(itemTable, Me.lvwEventsTab)
        lblEventTab.Content = String.Empty
    End Sub

    Private Sub LoadKeyDatesTab()
        Dim itemTable As System.Data.DataTable
        itemTable = CRM.BusinessLayer.Cases.GetKeyDates(CRM.BusinessLayer.GlobalCRM.CurrentCaseID)
        DataBinding.BindListView(itemTable, Me.lvwKeyDates)
    End Sub

    Public Function GblFunc_Populate_CaseStages(ByVal CaseID As Long) As Boolean


        Dim myData As System.Data.DataTable
        Dim SQL As StringBuilder
        Dim IntProductID As Integer, IntStageID As Integer, IntDiagram As Integer
        Dim IntBtn As Integer, IntCtype As Integer
        Dim myRow As DataRow
        Dim myButton As Button
        'Dim DB As New CRM.DataLayer.DataAccess()
        Me.btnStage1.Visibility = System.Windows.Visibility.Hidden
        Me.btnStage2.Visibility = System.Windows.Visibility.Hidden
        Me.btnStage3.Visibility = System.Windows.Visibility.Hidden
        Me.btnStage4.Visibility = System.Windows.Visibility.Hidden
        Me.btnStage5.Visibility = System.Windows.Visibility.Hidden
        Me.btnStage6.Visibility = System.Windows.Visibility.Hidden

        btnStage1.Content = String.Empty
        btnStage2.Content = String.Empty
        btnStage3.Content = String.Empty
        btnStage4.Content = String.Empty
        btnStage5.Content = String.Empty
        btnStage6.Content = String.Empty
        'If IsCo = 1 Then
        ' IntCtype = 2
        ' Else
        If GlobalCRM.CurrentCompanyID > 0 Then
            IntCtype = 2
        Else
            IntCtype = 1
        End If
        'End If

        If CaseID = 0 Then
            'No case, clear the form

            IntBtn = 1

            'Me.btnStage1.Visible = False
            'Me.btnStage2.Visible = False
            'Me.btnStage3.Visible = False
            'Me.btnStage4.Visible = False
            'Me.btnStage5.Visible = False
            'Me.btnStage6.Visible = False

            Return True
            Exit Function
        End If

        'Get product and stage details from the case
        SQL = New StringBuilder
        With SQL
            SQL.Append("Select Case_StatusID, Case_ProductID from D_Case where Case_Id = " & CaseID)
            myData = CommonDataFunctions.GetSQLDatatable(.ToString)
        End With

        If IsNothing(myData) Then
            Exit Function
        End If

        If myData.Rows.Count = 0 Then
            Exit Function
        End If



        IntProductID = myData.Rows(0).Item("Case_ProductID")
        IntStageID = myData.Rows(0).Item("Case_StatusID")

        myData.Dispose()

        If IntProductID = 0 Then
            'No prodcut, use no product diagram
            IntDiagram = 2
        Else
            IntDiagram = CRM.BusinessLayer.CommonDataFunctions.GblFunc_Get_Dataset(CaseID, 1)
        End If

        If IntDiagram = 0 Then IntDiagram = 2

        'Now know the current stage and the diagram its within, so begin to populate

        'Find out which advance buttons are needed
        SQL = New StringBuilder
        With SQL
            .Append("SELECT L_StageLinks.StageLink_Desc, L_StageLinks.StageLink_ToID, L_StageLinks.StageLink_Position, L_StageLinks.StageLink_Admin ")
            .Append("FROM L_StageLinks ")
            .Append("WHERE (L_StageLinks.StageLink_DiagramID = " & IntDiagram & ") ")
            .Append(" And (L_StageLinks.StageLink_FromID = " & IntStageID & ")")
            .Append(" And (L_StageLinks.StageLink_CustomerType in (0, " & IntCtype & "))")
            myData = CommonDataFunctions.GetSQLDatatable(.ToString)
        End With

        If Not myData Is Nothing Then

            If myData.Rows.Count = 0 Then
                myData.Dispose()
                'No links at all, do nothing
                Return True
                Exit Function
            End If
        Else
            Exit Function
        End If



        'Set the captions and make the buttons visible


        For Each myRow In myData.Rows

            'check for security
            If myRow.Item("StageLink_Admin") <> 0 Then
                If myRow.Item("StageLink_Admin") = 1 Then

                    For Each currentControl As FrameworkElement In grdStatus.Children

                        If currentControl.GetType() Is GetType(System.Windows.Controls.Button) Then
                            If currentControl.Name = "btnStage" & myRow.Item("StageLink_Position") Then
                                myButton = currentControl
                                myButton.Content = myRow.Item("stagelink_desc")
                                myButton.Visibility = System.Windows.Visibility.Visible
                            End If
                        End If
                    Next


                Else
                    'Admin only, dont make available
                    For Each currentControl As FrameworkElement In grdStatus.Children

                        If currentControl.GetType() Is GetType(System.Windows.Controls.Button) Then
                            If currentControl.Name = "btnStage" & myRow.Item("StageLink_Position") Then
                                myButton = currentControl
                                'myButton.Content = myRow.Item("stagelink_desc")
                                myButton.Visibility = System.Windows.Visibility.Visible
                            End If
                        End If
                    Next

                End If
            Else
                For Each currentControl As FrameworkElement In grdStatus.Children

                    If currentControl.GetType() Is GetType(System.Windows.Controls.Button) Then
                        If currentControl.Name = "btnStage" & myRow.Item("StageLink_Position") Then
                            myButton = currentControl
                            myButton.Content = myRow.Item("stagelink_desc")
                            myButton.Visibility = System.Windows.Visibility.Visible
                        End If
                    End If
                Next

            End If

            If myRow.Item("StageLink_ToID") = 999 Then 'SLA awaiting payment
                'If Form_Fm_MainDisplay.Page_Company.Visible = False Or Form_Fm_MainDisplay.Txt_Company_AccountType <> "SLA" Then
                If GlobalCRM.CurrentCompanyID = 0 Then

                    myButton.Visibility = System.Windows.Visibility.Hidden
                    'End If
                Else
                    'Hide if not SLA
                    If Company.GetAccountType(GlobalCRM.CurrentCompanyID) <> 2 Then
                        myButton.Visibility = System.Windows.Visibility.Hidden
                    End If

                End If
            End If


        Next

        myData.Dispose()

        If btnStage1.Content = String.Empty Then
            btnStage1.Visibility = System.Windows.Visibility.Hidden
        End If

        If btnStage2.Content = String.Empty Then
            btnStage2.Visibility = System.Windows.Visibility.Hidden
        End If

        If btnStage3.Content = String.Empty Then
            btnStage3.Visibility = System.Windows.Visibility.Hidden
        End If

        If btnStage4.Content = String.Empty Then
            btnStage4.Visibility = System.Windows.Visibility.Hidden
        End If

        If btnStage5.Content = String.Empty Then
            btnStage5.Visibility = System.Windows.Visibility.Hidden
        End If

        If btnStage6.Content = String.Empty Then
            btnStage6.Visibility = System.Windows.Visibility.Hidden
        End If

        Return True


    End Function

    Public Sub DisplayAccountsSummary(ByVal myAccountsSummary As Accounts.AccountsSummary)
        If Not IsNothing(myAccountsSummary) Then
            With myAccountsSummary
                Me.lblQuoteNet.Content = Format(.QuoteNet, m_strCurrencyChar & "0.00")
                Me.lblQuoteGross.Content = Format(.QuoteGross, m_strCurrencyChar & "0.00")
                Me.lblInvoiceNet.Content = Format(.InvoicedNet, m_strCurrencyChar & "0.00")
                Me.lblInvoiceGross.Content = Format(.InvoicedGross, m_strCurrencyChar & "0.00")
                Me.lblPayments.Content = Format(.Payments, m_strCurrencyChar & "0.00")
                Me.lblBalance.Content = Format(.Balance, m_strCurrencyChar & "0.00")
            End With
        End If
    End Sub

    Private Sub DisplayNewCaseStatus(Optional ByVal EditGrid As Boolean = False)

        Dim myStage As Cases.CaseStage = Cases.GetCaseStage(GlobalCRM.CurrentCaseID)

        If Not IsNothing(myStage) Then
            If myStage.ActiveStatus <> 1 Then
                Me.lblCaseStatus.Content = myStage.StageTitle
            Else
                Me.lblCaseStatus.Content = "ON HOLD: " & myStage.StageTitle
            End If
            Me.lblDateStatus.Content = Format(myStage.StageDateSet, "dd-MMM-yyyy")
        End If

        If EditGrid Then

            'Find data in grid and edit row, rather than reloading all of it.
            'Dim myRow As Xceed.Grid.DataRow

            'For Each myRow In Me.grdCases.DataRows
            '    If myRow.Cells("CaseID").Value = GlobalCRM.CurrentCaseID Then
            '        myRow.Cells("Status").Value = Me.lblCaseStatus.Text
            '        myRow.Cells("DateStatus").Value = Format(myStage.StageDateSet, "dd/MM/yyyy")
            '        Exit For
            '    End If
            'Next
        End If


    End Sub

    Private Sub ClearScreen()
        ' clear all details from last case viewed

        'Clear dependants
        Me.lblDependOfId.Content = String.Empty
        Me.lblDependOfName.Content = String.Empty
        Me.grpDependantOf.Visibility = System.Windows.Visibility.Hidden
        'Me.lvwDepend.Items.Clear()
        'Me.grpDependants.Visible = False

        'Clear Finance tab
        Me.lblQuoteNet.Content = String.Empty
        Me.lblQuoteGross.Content = String.Empty
        Me.lblInvoiceNet.Content = String.Empty
        Me.lblInvoiceGross.Content = String.Empty
        Me.lblPayments.Content = String.Empty
        Me.lblBalance.Content = String.Empty

        'Case Status
        Me.lblCaseStatus.Content = String.Empty
        Me.lblDateStatus.Content = String.Empty

        'Docstore
        Me.lblNoDocStore.Content = String.Empty
        Me.lblNoDocReq.Content = String.Empty
        Me.lblNoDocOut.Content = String.Empty

        'Events
        Me.lvwEventsTab.ItemsSource = Nothing
        Me.lvwEventsTab.Items.Clear()
        Me.lblEventTab.Content = String.Empty

        'Key dates
        Me.lvwKeyDates.ItemsSource = Nothing
        Me.lvwKeyDates.Items.Clear()

        Me.lblCandidateID2.Content = String.Empty
        Me.lblCandidateName2.Content = String.Empty
        Me.lblContactId.Content = String.Empty
        Me.lblContactName.Content = String.Empty

        Me.TabControl2.IsEnabled = False


        Me.btnEditCase.IsEnabled = False

        Me.btnSend.IsEnabled = False
        Me.btnInbox.IsEnabled = False
        Me.btnStockLetters.IsEnabled = False
        Me.btnAddCaseEvent.IsEnabled = False
        Me.btnViewCaseEvents.IsEnabled = False
        Me.btnAddCFF.IsEnabled = False
        Me.btnFileAudit.IsEnabled = False
        Me.btnCreditController.IsEnabled = False
        Me.btnRevertWriteOff.IsEnabled = False

    End Sub

    Private Sub LoadPhoneNumbers(ByVal PersonId As Long)
        'Dim myData As DataTable
        'Dim DB As New CRM.DataLayer.DataAccess()
        'myData = DB.GetSQLDataTable()
        DataBinding.BindListView(CRM.BusinessLayer.PrivateIndividual.GetPhoneNumbersSQL(PersonId), Me.lvwPhoneNumbers)
        Me.lvwPhoneNumbers.SelectedItems.Clear()
        Me.btnEditPhone.IsEnabled = False
        Me.btnMainPhone.IsEnabled = False
        Me.btnFaxPhone.IsEnabled = False
        Me.btnDeletePhone.IsEnabled = False
    End Sub

    Private Sub LoadEmailAddresses(ByVal PersonId As Long)
        'Dim myData As DataTable
        'Dim DB As New CRM.DataLayer.DataAccess()
        'myData = DB.GetSQLDataTable(CRM.BusinessLayer.PrivateIndividual.GetEmailAddressSQL(PersonId))
        DataBinding.BindListView(CRM.BusinessLayer.PrivateIndividual.GetEmailAddressSQL(PersonId), Me.lvwEmailAddress)
        Me.lvwEmailAddress.SelectedItems.Clear()
        Me.btnEditEmail.IsEnabled = False
        Me.btnMainEmail.IsEnabled = False
        Me.btnDeleteEmail.IsEnabled = False
        Me.btnSendEmail.IsEnabled = False
    End Sub

    Private Sub LoadAddresses(ByVal PersonId As Long)

        Dim intLineID As Integer = -1
        Dim intCtr As Integer
        Dim myData As System.Data.DataTable
        'Dim DB As New CRM.DataLayer.DataAccess()
        If PersonId > 0 Then
            myData = CRM.BusinessLayer.PrivateIndividual.GetPersonAddressSQL(PersonId)

            If Me.lvwAddresses.SelectedItems.Count > 0 Then
                'intLineID = Me.lvwAddresses.SelectedItems(0).Tag
                intLineID = CInt(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString)
            End If

            DataBinding.BindListView(myData, Me.lvwAddresses)

            Me.lvwAddresses.SelectedItems.Clear()
            Me.btnAddressEdit.IsEnabled = False
            Me.btnAddressDel.IsEnabled = False
            Me.btnAddressChangeToCo.IsEnabled = False
            Me.btnInvoiceAddress.IsEnabled = False
            Me.btnCorrespondence.IsEnabled = False

            If intLineID > -1 Then
                For intCtr = 0 To lvwAddresses.Items.Count - 1
                    If CInt(Me.lvwAddresses.Items(intCtr).row.itemarray(0).ToString) = intLineID Then
                        ' Me.lvwAddresses.Items(intCtr).Selected = True
                        Me.lvwAddresses.SelectedItems.Add(Me.lvwAddresses.Items(intCtr))

                    End If
                Next
            End If
        End If
    End Sub

    Private Sub ShowCandidateDetails(ByVal PersonId As Long)
        If PersonId > 0 Then
            Dim myPerson As People.PersonInfo = People.GetPerson(PersonId)
            Dim commonFunc As New CRM.BusinessLayer.CommonFuncs()
            With myPerson
                Me.lblCandidateName3.Text = .Firstname & " " & .Surname
                Me.lblPersonJob.Text = .JobTitle

                Me.lblPersonDOB.Text = commonFunc.FormatDate(.DOB)

                ' Me.lblPersonAge.Text = Convert.ToInt32(DateDiff(DateInterval.Year, .DOB, Date.Today))
                Me.lblPersonAge.Text = commonFunc.GetAge(.DOB)
                If Me.lblPersonAge.Text > 200 Then
                    Me.lblPersonAge.Text = String.Empty
                End If
                Me.lblPersonQualification.Text = .Qualification
                Me.lblPersonSalary.Text = .Salary
                Me.lblPersonPassportNo.Text = .PassportNo
                Me.lblPersonPassportExp.Text = commonFunc.FormatDate(.PassportExp)
                Me.lblPersonDest.Text = .DestinationName
                Me.lblPersonNat.Text = .NationalityName
                Me.lblPersonRes.Text = .ResidenceName
                Me.lblPersonUKVisa.Text = .UKVisaName
                Me.lblPersonVisaExp.Text = commonFunc.FormatDate(.UKVisaExpiry)
                'Me.lblPersonAccMan.Content = CommonDataFunctions.GetConsultantName(.AccountManagerId)
                Me.lblPersWhereHeard.Content = .WhereHeard
                Me.lblSkillOcc.Text = .SkillOccupationName
            End With

            If myPerson.SkilledOccupationId > 0 Then
                Me.lblSkillOcc.Visibility = System.Windows.Visibility.Visible
                Me.lblSkillOccLbl.Visibility = System.Windows.Visibility.Visible
            Else
                Me.lblSkillOcc.Visibility = System.Windows.Visibility.Hidden
                Me.lblSkillOccLbl.Visibility = System.Windows.Visibility.Hidden
            End If
        End If
    End Sub

    Private Sub LoadCompanyInfo()

        Dim myComp As Company.CompanyInfo = Company.GetCompany(GlobalCRM.CurrentCompanyID)

        With myComp
            Me.lblCompanyID.Content = .CompanyID
            Me.lblCompanyName.Text = .CompanyName
            Me.lblCompanySize.Content = .CompanySize
            Me.lblDateEntered.Content = .DateEntered
            Me.lblEnteredBy.Content = .EnteredBy
            Me.lblIndustry.Content = .IndustryName
            Me.lblWebsite.Content = .Website
            Me.lblAccManager.Content = .AccountManager
            Me.lblDefCW.Content = .DefaultCaseWorker

            Me.lblCandidateName.Text = .CompanyName
            Me.lblCandidateID.Text = .CompanyID
            Me.lblAccType.Content = .AccountType
            Me.lblCompanyStatus.Content = .CompanyStatus

            Me.lblWhereHeard.Content = Company.GetCompanyWhereHeard(.CompanyID)

            If .ParentCompanyId > 0 Then
                Me.grpParent.Visibility = System.Windows.Visibility.Visible
                Me.lblParentCompId.Content = .ParentCompanyId
                Me.lblParentCompName.Content = Company.GetCompany(.ParentCompanyId).CompanyName

            Else
                Me.grpParent.Visibility = System.Windows.Visibility.Hidden
            End If

        End With

    End Sub

    Private Sub LoadCompanyAddresses()
        Dim intLineID As Integer = -1
        Dim intCtr As Integer

        If Me.lvwCoAddresses.Items.Count > 0 Then
            'intLineID = Me.lvwAddresses.SelectedItems(0).Tag
            If Me.lvwCoAddresses.SelectedItems.Count > 0 Then
                intLineID = CInt(Me.lvwCoAddresses.SelectedItem.row.itemarray(0).ToString)
            End If
        End If
        Dim corporateAddresses As System.Data.DataTable
        'dim strCorporateAddresses As String = Company.GetCorporateAddresses(GlobalCRM.CurrentCompanyID)
        corporateAddresses = Company.GetCorporateAddresses(GlobalCRM.CurrentCompanyID)
        DataBinding.BindListView(corporateAddresses, Me.lvwCoAddresses)

        If intLineID > -1 Then
            For intCtr = 0 To lvwCoAddresses.Items.Count - 1
                If CInt(Me.lvwCoAddresses.Items(intCtr).row.itemarray(0).ToString) = intLineID Then
                    'Me.lvwCoAddresses.Items(intCtr).isSelected = True

                    lvwCoAddresses.SelectedItem = intCtr
                End If
            Next
        End If
    End Sub

    Private Sub btnWebLogin_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnWebLogin.Click
        Dim WebForm As New frmWebLogin()
        WebForm.PersonId = lblCandidateId3.Text
        WebForm.ShowDialog()
    End Sub

    Private Sub btnDocStore_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDocStore.Click
        'Dim frmdocstore As New frmDocumentStore
        'frmdocstore.ShowDialog() -- 
        ''
        'RaiseEvent ShowDynamicTab("document")

        loadTabDocs = False
        Me.TabControl1.SelectedItem = Me.tabDocuments
        'tabDocuments_GotFocus(sender, e)
    End Sub

    Private Sub btnAddtoCompany_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddtoCompany.Click
        Dim frmAddPersonToCompany As New frmAddPersonToCompany
        frmAddPersonToCompany.ShowDialog()
    End Sub

    Private Sub btnAddPyPlan_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddPyPlan.Click
        Dim frmPaymentPlan As New frmPaymentPlan
        frmPaymentPlan.ShowDialog()
    End Sub

    Private Sub btnRemoveSubsid_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRemoveSubsid.Click
        If Not Me.lvwSubsidiary.SelectedItem Is Nothing Then
            If MsgBox("Are you sure you want to remove '" & Me.lvwSubsidiary.SelectedItem.row.itemarray(1).ToString & "' as a subsidiary?", vbYesNo + vbExclamation, "Confirm Delete") <> MsgBoxResult.Yes Then
                Exit Sub
            End If

            If Company.RemoveSubsidiary(GlobalCRM.CurrentCompanyID, GlobalCRM.CurrentCompanyName, Me.lvwSubsidiary.SelectedItem.row.itemarray(0).ToString, Me.lvwSubsidiary.SelectedItem.row.itemarray(1).ToString) Then
                DataBinding.BindListView(CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID), Me.lvwSubsidiary)
            End If
        End If
    End Sub

    Private Sub btnEditCompany_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditCompany.Click
        Dim frmCompanyDetails As New frmCompanyDetails
        frmCompanyDetails.ShowDialog()
        Me.LoadCompanyInfo()
    End Sub

    Private Sub btnAddCompEvent_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddCompEvent.Click
        Dim frmAddEvent As New frmAddEvent
        Try

            With frmAddEvent
                .EventType = TasksEvents.EventTypes.EventCompany
                .LinkId = GlobalCRM.CurrentCompanyID
                .ShowDialog()
            End With

            Me.RefreshEventList()
        Catch ex As Exception

        Finally
            frmAddEvent = Nothing
        End Try
    End Sub

    Private Sub btnCompanyEvents_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCompanyEvents.Click
        Me.TabControl1.SelectedItem = Me.tabEvent
        Me.radEventCompany.IsChecked = True
    End Sub

    Private Sub btnCompanyAdverts_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCompanyAdverts.Click
        CommonFuncs.DisplayMessage("This facility has not been added yet.", CommonDialog.CustomDialogIcons.Information, String.Empty)
    End Sub

    Private Sub btnEditSLA_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditSLA.Click
        Dim frmSLACharges As New frmSLACharges

        frmSLACharges.ShowDialog()
    End Sub

    Private Sub btnAddSubsidiary_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddSubsidiary.Click
        Dim frmAddCompanyLink As New frmAddCompanyLink
        With frmAddCompanyLink
            .ScreenMode = frmAddCompanyLink.LinkMode.Subsidiary
            .ShowDialog()
        End With
        DataBinding.BindListView(CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID), Me.lvwSubsidiary)
    End Sub

    Private Sub btnSetParentCompany_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSetParentCompany.Click
        Dim frmAddCompanyLink As New frmAddCompanyLink
        With frmAddCompanyLink
            .ScreenMode = frmAddCompanyLink.LinkMode.Parent
            .ShowDialog()
        End With
        DataBinding.BindListView(CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID), Me.lvwSubsidiary)
        Me.LoadCompanyInfo()
    End Sub

    Private Sub btnAddPersToComp_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddPersToComp.Click
        Dim frmAddPerson As New frmAddPerson
        frmAddPerson.ShowDialog()
        DataBinding.BindListView(Company.GetCorporateContacts(GlobalCRM.CurrentCompanyID), Me.lvwContacts)
        DataBinding.BindListView(Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.All), Me.lvwPeopleList)
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddCoAddress.Click
        Dim frmAddAddress As New frmAddAddress
        With frmAddAddress
            .AddressType = People.AddressTypes.Company
            '.Content = "Add New Address"
            .Address1.CountryComboBox.DisplayMemberPath = "country_name"
            .Address1.CountryComboBox.SelectedValuePath = "country_id"
            .Address1.CountryComboBox.ItemsSource = CType(CommonDataFunctions.CountryList, IListSource).GetList
            .Address1.CountryComboBox.SelectedIndex = -1
            .ShowDialog()
        End With

        'frmAddAddress.AddressType = People.AddressTypes.Company
        'frmAddAddress.ShowDialog()

        Me.LoadCompanyAddresses()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditCoAddress.Click
        Dim frmAddAddress As New frmAddAddress
        If Me.lvwCoAddresses.SelectedItems.Count = 0 Then
            MsgBox("No address selected.")
            Exit Sub
        End If

        With frmAddAddress
            .AddressType = People.AddressTypes.Company
            .AddressLinkId = Me.lvwCoAddresses.SelectedItem.row.itemarray(0).ToString
            .Title = "Edit Address"
            .Address1.CountryComboBox.DisplayMemberPath = "country_name"

            .Address1.CountryComboBox.SelectedValuePath = "country_id"
            .Address1.CountryComboBox.ItemsSource = CType(CommonDataFunctions.CountryList, IListSource).GetList
            .ShowDialog()
            .ShowInTaskbar = True
        End With

        Me.LoadCompanyAddresses()
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCoCorrAddress.Click
        If Me.lvwCoAddresses.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("No address selected.", CommonDialog.CustomDialogIcons.Information, "Address")
            Exit Sub
        End If

        If Company.SetCorrespOrInvAddress(Me.lvwCoAddresses.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCompanyID, Me.lvwCoAddresses.SelectedItem.row.itemarray(3).ToString, Company.AddressLinkTypes.Correspondence, Me.lvwCoAddresses.SelectedItem.row.itemarray(4).ToString) = True Then
            Me.LoadCompanyAddresses()
        End If
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDelCoAddress.Click
        If Me.lvwCoAddresses.SelectedItems.Count = 0 Then
            Exit Sub
        End If

        If People.DeleteAddress(Me.lvwCoAddresses.SelectedItem.row.itemarray(0).ToString, People.AddressTypes.Company) Then
            Me.LoadCompanyAddresses()
        End If
    End Sub

    Private Sub lvwCoAddresses_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles lvwCoAddresses.SelectionChanged

        If Me.lvwCoAddresses.SelectedItems.Count > 0 Then
            Me.btnEditCoAddress.IsEnabled = True
            Me.btnDelCoAddress.IsEnabled = True
            Me.btnCoInvAddress.IsEnabled = True
            Me.btnCoCorrAddress.IsEnabled = True
        Else
            Me.btnEditCoAddress.IsEnabled = False
            Me.btnDelCoAddress.IsEnabled = False
            Me.btnCoInvAddress.IsEnabled = False
            Me.btnCoCorrAddress.IsEnabled = False
        End If

        ' display full address
        If Me.lvwCoAddresses.SelectedItems.Count > 0 Then
            Dim myAddress As People.AddressInfo = People.GetAddress(Me.lvwCoAddresses.SelectedItem.row.itemarray(0).ToString)
            Dim sbAddress As New StringBuilder
            sbAddress.Append(myAddress.AddressText & vbCrLf)
            sbAddress.Append(myAddress.Region & vbCrLf)
            sbAddress.Append(myAddress.Postcode & vbCrLf)
            sbAddress.Append(myAddress.CountryName)
            lblCoAddressFull.Content = sbAddress.ToString
        End If
    End Sub


    Private Sub btnAddEventPerson_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddEventPerson.Click
        Dim frmAddEvent As New frmAddEvent
        Try
            If GlobalCRM.CurrentCandidateID > 0 Then
                frmAddEvent.EventType = TasksEvents.EventTypes.EventPerson
                frmAddEvent.LinkId = Me.lblCandidateId3.Text.ToString
                frmAddEvent.ShowDialog()
            End If

            Me.RefreshEventList()
        Catch ex As Exception
            frmAddEvent = Nothing
        End Try
    End Sub

    Private Sub btnViewEventPerson_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnViewEventPerson.Click
        If GlobalCRM.CurrentCandidateID > 0 Then
            Me.TabControl1.SelectedItem = Me.tabEvent
            Me.radEventPerson.IsChecked = True
        End If
    End Sub

    Private Sub btnEditPerson_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditPerson.Click
        Dim frmEditPerson As New frmEditPerson
        Try
            If GlobalCRM.CurrentCandidateID > 0 Then
                frmEditPerson.ShowDialog()
                Me.ShowCandidateDetails(Me.ActivePersonId)
                If GlobalCRM.CurrentCompanyID > 0 Then
                    DataBinding.BindListView(Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.All), Me.lvwPeopleList)
                End If
            End If
        Catch ex As Exception
        Finally

            frmEditPerson = Nothing
        End Try
    End Sub

    Private Sub btnAddPhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddPhone.Click
        Dim frmAddPhone As New frmAddPhone
        Try
            frmAddPhone.ShowDialog()
            frmAddPhone.Content = "Add Phone Number"
            Me.LoadPhoneNumbers(Me.ActivePersonId)
        Catch ex As Exception
        Finally

            frmAddPhone = Nothing
        End Try
    End Sub

    Private Sub btnEditPhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditPhone.Click
        Dim frmAddPhone As New frmAddPhone
        Try


            With frmAddPhone
                .Title = "Edit Phone Number"
                .PhoneId = Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString
                .txtPhoneNumber.Text = Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString
                .txtPhoneTitle.Text = Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString
                .ShowDialog()
            End With
            Me.LoadPhoneNumbers(Me.ActivePersonId)
        Catch ex As Exception
            frmAddPhone = Nothing
        End Try
    End Sub

    Private Sub btnMainPhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnMainPhone.Click

        If Me.lvwPhoneNumbers.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select a phone number first!", CommonDialog.CustomDialogIcons.Information, "Select")
            Exit Sub
        Else
            Select Case Me.lvwPhoneNumbers.SelectedItem.row.itemarray(3).ToString

                Case "Main", "Both"
                    'Is already set to main
                    Call CommonFuncs.DisplayMessage("Already set as the main number!", CommonDialog.CustomDialogIcons.Information, "Main Number")
                    Exit Sub

                Case "Fax"
                    'Set to both
                    People.SetMainOrFaxPhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, People.PhoneTypes.PhoneBoth, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)

                Case Else
                    'Not set, so set to main
                    People.SetMainOrFaxPhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, People.PhoneTypes.PhoneMain, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)

            End Select
        End If
    End Sub

    Private Sub btnFaxPhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnFaxPhone.Click
        If Me.lvwPhoneNumbers.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select a phone number first!", CommonDialog.CustomDialogIcons.Information, "Phone/Fax")
            Exit Sub
        Else
            Select Case Me.lvwPhoneNumbers.SelectedItem.row.itemarray(3).ToString

                Case "Fax", "Both"
                    'Is already set to Fax
                    Call CommonFuncs.DisplayMessage("Already set as the Fax number!", CommonDialog.CustomDialogIcons.Information, "Fax Number")
                    Exit Sub

                Case "Main"
                    'Set to both
                    People.SetMainOrFaxPhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, People.PhoneTypes.PhoneBoth, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)

                Case Else
                    'Not set, so set to fax
                    People.SetMainOrFaxPhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, People.PhoneTypes.PhoneFax, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)

            End Select
        End If
    End Sub

    Private Sub btnDeletePhone_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDeletePhone.Click

        If Me.lvwPhoneNumbers.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select a phone number first!", CommonDialog.CustomDialogIcons.Information, "Delete Phone")
            Exit Sub
        ElseIf Me.lvwPhoneNumbers.Items.Count = 1 Then
            If MsgBox("This is the only number listed for this person, are you sure you want to delete it?", vbYesNo + vbExclamation, "Confirm Delete") = MsgBoxResult.Yes Then
                People.DeletePhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                Me.LoadPhoneNumbers(Me.ActivePersonId)
            Else
                Exit Sub
            End If
        Else
            If Me.lvwPhoneNumbers.SelectedItem.row.itemarray(3).ToString = "Main" Then
                'Refuse to delete
                CommonFuncs.DisplayMessage("That is the main number for this person, please select another number as the main number before deleting this one.", CommonDialog.CustomDialogIcons.Information, "Main Number")
                Exit Sub
            Else
                If MsgBox("Are you sure you want to delete the phone number " & Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString & "?", vbYesNo + vbExclamation, "Confirm Delete") = MsgBoxResult.Yes Then
                    People.DeletePhoneNumber(Me.lvwPhoneNumbers.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(1).ToString, Me.lvwPhoneNumbers.SelectedItem.row.itemarray(2).ToString)
                    Me.LoadPhoneNumbers(Me.ActivePersonId)
                End If
            End If
        End If
    End Sub

    Private Sub btnAddEmail_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddEmail.Click
        Dim frmAddEmail As New frmAddEmail
        Try


            frmAddEmail.ShowDialog()
            frmAddEmail.Content = "Add Email Address"
            Me.LoadEmailAddresses(Me.ActivePersonId)
        Catch ex As Exception
        Finally
            frmAddEmail = Nothing
        End Try

    End Sub

    Private Sub btnEditEmail_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditEmail.Click
        Dim frmAddEmail As New frmAddEmail
        Try
            With frmAddEmail
                .EMailId = Me.lvwEmailAddress.SelectedItem.row.itemarray(0).ToString
                .Title = "Edit Email Address"
                .txtEmailAddress.Text = Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString
                '.cboDescription.Text = Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString
                ._cboDesc = Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString
                .ShowDialog()
            End With
            Me.LoadEmailAddresses(Me.ActivePersonId)
        Catch ex As Exception
        Finally
            frmAddEmail = Nothing
        End Try

    End Sub

    Private Sub btnMainEmail_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnMainEmail.Click

        If Me.lvwEmailAddress.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select an email address first!", CommonDialog.CustomDialogIcons.Information, "Select Email Address")
            Exit Sub
        End If

        If Me.lvwEmailAddress.SelectedItem.row.itemarray(3).ToString = "Main" Then
            CommonFuncs.DisplayMessage("Already set as main address!", CommonDialog.CustomDialogIcons.Information, "Email Address")
            Exit Sub
        End If

        If People.SetMainEmailAddress(Me.lvwEmailAddress.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString, Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString) Then
            Me.LoadEmailAddresses(Me.ActivePersonId)
        End If

    End Sub

    Private Sub btnDeleteEmail_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDeleteEmail.Click
        If Me.lvwEmailAddress.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select an email address first!", CommonDialog.CustomDialogIcons.Information, "Email Address")
            Exit Sub
        ElseIf Me.lvwEmailAddress.Items.Count = 1 Then
            If MsgBox("This is the only email address listed for this person, are you sure you want to delete it?", vbYesNo + vbExclamation, "Confirm Delete") = MsgBoxResult.Yes Then
                If People.DeleteEmailAddress(Me.lvwEmailAddress.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString, Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString) Then
                    Me.LoadEmailAddresses(Me.ActivePersonId)
                End If
            Else
                Exit Sub
            End If
        Else
            If Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString = "Main" Then
                'Refuse to delete
                CommonFuncs.DisplayMessage("That is the main email address for this person, please select another email as the main email before deleting this one.", CommonDialog.CustomDialogIcons.Information, "Mail Email Address")
                Exit Sub
            Else
                If MsgBox("Are you sure you want to delete the email address " & Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString & "?", vbYesNo + vbExclamation, "Confirm Delete") = MsgBoxResult.Yes Then

                    If People.DeleteEmailAddress(Me.lvwEmailAddress.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwEmailAddress.SelectedItem.row.itemarray(1).ToString, Me.lvwEmailAddress.SelectedItem.row.itemarray(2).ToString) Then
                        Me.LoadEmailAddresses(Me.ActivePersonId)
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub btnAddressAdd_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddressAdd.Click
        Dim frmAddAddress As New frmAddAddress
        Try


            With frmAddAddress
                .AddressType = People.AddressTypes.Person
                .Title = "Add New Address"
                '.Address1.drpCountry.DisplayMember = "country_name"
                '.Address1.drpCountry.ValueMember = "country_id"
                '.Address1.drpCountry.DataSource = CommonSQL.CountryList
                '.Address1.drpCountry.SelectedIndex = -1
                .ShowDialog()
            End With

            Me.LoadAddresses(Me.ActivePersonId)
        Catch ex As Exception
        Finally
            frmAddAddress = Nothing

        End Try
    End Sub

    Private Sub btnAddressEdit_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddressEdit.Click
        Dim frmAddAddress As New frmAddAddress
        Try


            If lvwAddresses.SelectedItems.Count > 0 Then
                With frmAddAddress
                    .AddressType = People.AddressTypes.Person
                    .AddressLinkId = Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString
                    '.Text = "Edit Address"
                    '.Address1.drpCountry.DisplayMember = "country_name"
                    '.Address1.drpCountry.ValueMember = "country_id"
                    '.Address1.drpCountry.DataSource = CommonSQL.CountryList
                    .ShowDialog()
                    '.AddressType = People.AddressTypes.Person
                    '.AddressLinkId = Me.lvwAddresses.SelectedItems(0).SubItems(0).Text
                    '.Text = "Edit Address"
                    '.Address1.txtDescription.Text = Me.lvwAddresses.SelectedItems(0).SubItems(2).Text
                    '.Address1.txtAddress.Text = Me.lvwAddresses.SelectedItems(0).SubItems(4).Text
                    '.ShowDialog()
                End With
                Me.LoadAddresses(Me.ActivePersonId)
            Else
                CommonFuncs.DisplayMessage("No address selected.", CommonDialog.CustomDialogIcons.Information, "Address")
            End If
        Catch ex As Exception
        Finally
            frmAddAddress = Nothing
        End Try
    End Sub

    Private Sub btnAddressDel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddressDel.Click

        If Me.lvwAddresses.SelectedItems.Count = 0 Then
            Exit Sub
        End If

        If People.DeleteAddress(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString, People.AddressTypes.Person, GlobalCRM.CurrentCandidateName) Then
            Me.LoadAddresses(Me.ActivePersonId)
        End If
    End Sub

    Private Sub btnCorrespondence_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCorrespondence.Click

        Dim ChangeTo As People.AddressLinkTypes

        If Me.lvwAddresses.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select an address first", CommonDialog.CustomDialogIcons.Information, "Select Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Cor" Or Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Both" Then
            CommonFuncs.DisplayMessage("This is already marked as the correspondence address", CommonDialog.CustomDialogIcons.Information, "Correspondence Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Inv" Then
            ChangeTo = People.AddressLinkTypes.Both
        Else
            ChangeTo = People.AddressLinkTypes.Correspondence
        End If

        If People.SetCorrespOrInvAddress(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwAddresses.SelectedItem.row.itemarray(1).ToString, ChangeTo) Then
            Me.LoadAddresses(Me.ActivePersonId)
        End If
    End Sub

    Private Sub btnInvoiceAddress_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnInvoiceAddress.Click

        Dim ChangeTo As People.AddressLinkTypes

        If Me.lvwAddresses.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select an address first", CommonDialog.CustomDialogIcons.Information, "Select Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString = "Inv" Or Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Both" Then
            CommonFuncs.DisplayMessage("This is already marked as the invoice address", CommonDialog.CustomDialogIcons.Information, "Invoice Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(3).ToString = "Cor" Then
            ChangeTo = People.AddressLinkTypes.Both
        Else
            ChangeTo = People.AddressLinkTypes.Invoice
        End If

        If People.SetCorrespOrInvAddress(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCandidateID, Me.lvwAddresses.SelectedItem.row.itemarray(1).ToString, ChangeTo) Then
            Me.LoadAddresses(Me.ActivePersonId)
        End If
    End Sub

    Private Sub btnAddressChangeToCo_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddressChangeToCo.Click

        Dim CompAddr As String

        If Me.lvwAddresses.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select an address first", CommonDialog.CustomDialogIcons.Information, "Select Address")
            Exit Sub
        End If

        If Me.lvwAddresses.SelectedItem.row.itemarray(2).ToString = "Co" Then
            CommonFuncs.DisplayMessage("This is already a company address", CommonDialog.CustomDialogIcons.Information, "Company Address")
            Exit Sub
        End If

        CompAddr = InputBox("Please enter the name you wish the address to have with the company", "Send Address to Company", Me.lvwAddresses.SelectedItem.row.itemarray(1).ToString)

        If CompAddr.Trim = String.Empty Then
            CommonFuncs.DisplayMessage("Cannot have a blank name", CommonDialog.CustomDialogIcons.Information, "Blank Name")
            Exit Sub
        End If

        If People.SetAddressAsCompany(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentConName, GlobalCRM.CurrentCompanyID, CompAddr.Trim) Then
            Me.LoadAddresses(Me.ActivePersonId)
            Me.LoadCompanyAddresses()
        End If
    End Sub

    Private Sub btnWeb_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnWeb.Click
        Dim strWebAddress As String = Me.lblWebsite.Content

        If Mid(strWebAddress, 1, 7) = "http://" Then
            ' do nothing
        Else
            strWebAddress = "http://" & strWebAddress
        End If

        System.Diagnostics.Process.Start(strWebAddress)
    End Sub

    Private Sub btnDepend_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDepend.Click
        Dim frmDependants As New frmDependants
        Try


            frmDependants.ShowDialog()

            ' grab current person for later
            Dim PersonID As Long = GlobalCRM.CurrentCandidateID

            If frmDependants._AddNewPerson Then
                frmDependants.Close()
                Dim frmAddPerson As New frmAddPerson
                Try


                    With frmAddPerson
                        'Form_Fm_AddPerson.Txt_CompanyID.Visible = False
                        .drpRelationship.Visibility = System.Windows.Visibility.Hidden

                        'Where Hear value will be set to 'Dependant' automaticaly
                        .grpAdvert.Visibility = System.Windows.Visibility.Hidden

                        ' xxx you need to sort out passing the Dependents ID to the add person form
                        ' xxx add a label on the add person form and pass this value to it
                        ' xxx then pick up the value from label when user clicks on Save button
                        ._Dependant = GlobalCRM.CurrentCandidateID

                        .grpDependentOf.Visibility = System.Windows.Visibility.Visible
                        .lblParentID.Visibility = System.Windows.Visibility.Visible
                        .lblParentID.Content = GlobalCRM.CurrentCandidateID
                        .lblParentDesc.Visibility = System.Windows.Visibility.Visible
                        .lblParentDesc.Content = GlobalCRM.CurrentDependentParentDescription
                        .lblChildDesc.Visibility = System.Windows.Visibility.Visible
                        .lblChildDesc.Content = GlobalCRM.CurrentDependentChildDescription

                        .ShowDialog()

                        frmDependants.Close()

                        ' return to current person (otherwise added person becomes the current person)
                        GlobalCRM.CurrentCandidateID = PersonID

                    End With
                Catch ex As Exception

                End Try
            Else
                frmDependants.Close()
            End If

            ' refresh dependants
            DataBinding.BindListView(People.GetDependants(GlobalCRM.CurrentCandidateID), Me.lvwDepend)
        Catch ex As Exception

        End Try
    End Sub

    Private Sub btnCreditController_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCreditController.Click
        Dim tsk As New TasksEvents
        Try


            Dim caseid As Long = GlobalCRM.CurrentCaseID

            'Dim PaidAmt, GrossInv As Object
            Dim writeoffamount As Double
            'Dim dt As DataTable
            'Dim row As DataRow

            If MsgBox("Are you sure you want to write off the case : " & caseid, MsgBoxStyle.YesNo, "WriteOff") = MsgBoxResult.Yes Then

                'Dim i As Integer
                Dim blnWrittenoff As Boolean = False

                blnWrittenoff = False
                caseid = GlobalCRM.CurrentCaseID
                GlobalCRM.CurrentCaseID = caseid
                Dim statusid As Long
                statusid = CInt(CommonDataFunctions.GetStatusFromCase(caseid))
                If statusid = 2000 Then
                    CommonFuncs.DisplayMessage("The case has already been written off", CommonDialog.CustomDialogIcons.Information, "Already Written Off")

                    Exit Sub
                End If
                If CommonDataFunctions.WriteOffFinance(caseid) = True Then
                    If MsgBox("Would you like to close the case now?", MsgBoxStyle.YesNo, "Close the case?") = MsgBoxResult.Yes Then
                        Dim status As String = CommonDataFunctions.getCaseStageTitle(caseid)
                        If status <> "" Then
                            CommonDataFunctions.UpdateCaseStatus(status, "Written-Off")
                            CommonDataFunctions.UpdateCaseStatusNo(statusid, 2000)
                        End If

                        If CommonDataFunctions.UpdateStatusAsWriteoff(caseid) = True Then
                            CommonDataFunctions.CompleteTasksForCase(caseid)
                            tsk.GblFunc_Add_Event("File Written Off", "The file has been written off by : " & GlobalCRM.CurrentConName, TasksEvents.EventStatus.SingleEvent, caseid, TasksEvents.EventTypes.EventCase)
                            CommonFuncs.DisplayMessage("The case " & caseid & "  has been written off successfully.", CommonDialog.CustomDialogIcons.Information, "Success")

                        Else
                            CommonFuncs.DisplayMessage("There was an error in writing off the case " & caseid & "  .Please contact IT", CommonDialog.CustomDialogIcons.Information, "Error")
                        End If
                    End If
                    'refresh main page
                    SelectedCaseChanged()
                End If

            Else
                CommonFuncs.DisplayMessage("There was an error in writing off the case. Please contact IT", CommonDialog.CustomDialogIcons.Information, "Write Off")
            End If
            CommonFuncs.DisplayMessage("Amount to be written off : " & writeoffamount, CommonDialog.CustomDialogIcons.Information, "Write off")
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : btnCreditController_Click")
        Finally
            tsk = Nothing
        End Try
    End Sub

    Private Sub btnRevertWriteOff_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRevertWriteOff.Click
        If CommonFuncs.ISCaseWrittenOff(GlobalCRM.CurrentCaseID) = True Then
            Dim frmrevertWriteOff As New frmrevertWriteOff
            frmrevertWriteOff.ShowDialog()
            SelectedCaseChanged()
        Else
            CommonFuncs.DisplayMessage("The case was never written off, Please try a different case", CommonDialog.CustomDialogIcons.Information, "Case Already Written-Off")
        End If
    End Sub

    Private Sub btnViewCaseEvents_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnViewCaseEvents.Click
        loadTabEvent = False
        Me.TabControl1.SelectedItem = Me.tabEvent

        Me.radEventCase.IsChecked = True
        Me.drpEventView.SelectedValue = GlobalCRM.CurrentCaseID
    End Sub

    Private Sub btnAddCaseEvent_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddCaseEvent.Click
        Dim frmAddEvent As New frmAddEvent
        Try


            frmAddEvent.EventType = TasksEvents.EventTypes.EventCase
            frmAddEvent.LinkId = GlobalCRM.CurrentCaseID
            frmAddEvent.ShowDialog()
            Me.RefreshEventList()
        Catch ex As Exception
        Finally
            frmAddEvent = Nothing
        End Try
    End Sub

    Private Sub btnStockLetters_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnStockLetters.Click
        Dim frmStockLetters As New frmStockLetters
        frmStockLetters.ShowDialog()
        frmStockLetters = Nothing
    End Sub

    Private Sub btnInbox_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnInbox.Click
        If Environment.UserDomainName.ToUpper = "GV" Then
            'Dim frmMailbox As New frmMailbox
            Try


                'frmMailbox.MdiParent = frmMDIMain
                'frmMailbox.Show()
                'frmMailbox = Nothing
            Catch ex As Exception
                CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay.xaml:btnInbox_Click:frmMailbox")
            Finally
                'frmMailbox = Nothing

            End Try
        Else
            'call the component
            'Dim ImapClient As New ImapClientDemo.ImapClient
            Try

                'ImapClient.Show()
            Catch ex As Exception
                CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay.xaml:btnInbox_Click:ImapClient")
            Finally
                'ImapClient = Nothing

            End Try
        End If
    End Sub

    Private Sub btnEditCase_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEditCase.Click
        Dim frmEditCase As New frmEditCase
        frmEditCase.ShowDialog()
        Me.CaseViewChanged(Me, New System.EventArgs)
        Me.SelectActiveCase()
    End Sub

    Private Sub AddRegValue(ByVal caseid As Long)
        Dim CReg As New CReg
        'Dim value As String = 
        CReg.WriteValue(GlobalCRM.CRMVISA, GlobalCRM.CUST, GlobalCRM.Reg_CurrentCASEID, caseid)
        CReg = Nothing
    End Sub
    'Private Sub SelectActiveCase()
    '    '        Dim myRow As Xceed.Grid.CellRow   ' DataGridViewRow
    '    Dim myRow As DataRow  ' DataGridViewRow
    '    'Me.grdCases.SelectedRecords.Clear()

    '    For Each myRow In Me.grdCases.ItemsSource.rows
    '        If myRow.Item(0).ToString = GlobalCRM.CurrentCaseID Then
    '            Me.grdCases.SelectedItems.Add(myRow)
    '            AddRegValue(GlobalCRM.CurrentCaseID)
    '            Exit For
    '        Else
    '        End If
    '    Next
    'End Sub
    Private Sub SelectActiveCase()

        '        Dim myRow As Xceed.Grid.CellRow   ' DataGridViewRow

        Dim myRow As DataRow  ' DataGridViewRow
        'Dim i As Integer
        'Me.grdCases.SelectedRecords.Clear()

        If Not Me.grdCases Is Nothing Then

            If Me.grdCases.ItemsSource.rows.Count > 0 Then

                For Each myRow In Me.grdCases.ItemsSource.rows

                    If myRow.Item(0).ToString = GlobalCRM.CurrentCaseID Then

                        Me.grdCases.SelectedItems.Add(myRow)

                        AddRegValue(GlobalCRM.CurrentCaseID)

                        Exit For

                    Else

                    End If

                Next

            End If

        End If

    End Sub

    Private Sub SelectedCase_Active()

        '        Dim myRow As Xceed.Grid.CellRow   ' DataGridViewRow

        Dim myRow As DataRow  ' DataGridViewRow
        Dim i As Integer
        'Me.grdCases.SelectedRecords.Clear()

        If Not Me.grdCases Is Nothing Then
            If Not Me.grdCases.ItemsSource Is Nothing Then
                If Me.grdCases.ItemsSource.rows.Count > 0 Then

                    For i = 0 To Me.grdCases.ItemsSource.rows.Count - 1
                        If grdCases.ItemsSource.rows(i).itemarray(0).ToString = GlobalCRM.CurrentCaseID Then
                            myRow = grdCases.ItemsSource.rows(i)

                            Me.grdCases.SelectedItem = myRow
                            rowselectionchanged = False
                            Me.grdCases_SelectedRowsChanged(myRow, New System.EventArgs)
                            AddRegValue(GlobalCRM.CurrentCaseID)
                            Exit For
                        End If
                    Next
                End If
            End If

        End If
        TabControl1.SelectedItem = tabCase
        ' Me.DocumentStore_Loaded()
    End Sub

    Private Sub btnSearch_Click1(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSearch.Click
        Try
            Dim SearchForm As New frmSearch()
            SearchForm.ShowDialog()
            RaiseEvent ShowDynamicTab("maindisplay")
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.btnSearch_Click", False)
        End Try
    End Sub

    Private Sub btnViewCaseFinance_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnViewCaseFinance.Click
        Dim myAccountsSummary As Accounts.AccountsSummary
        Dim frmfinance As New frmFinances
        frmfinance.ShowDialog()
        myAccountsSummary = Accounts.GetAccountsSummary(GlobalCRM.CurrentCaseID)
        DisplayAccountsSummary(myAccountsSummary)
        SelectedCaseChanged()
    End Sub

    Private Sub lvwEmailAddress_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles lvwEmailAddress.SelectionChanged
        If Me.lvwEmailAddress.SelectedItems.Count > 0 Then
            Me.btnEditEmail.IsEnabled = True
            Me.btnDeleteEmail.IsEnabled = True
            Me.btnMainEmail.IsEnabled = True
            Me.btnSendEmail.IsEnabled = True
        Else
            Me.btnEditEmail.IsEnabled = False
            Me.btnDeleteEmail.IsEnabled = False
            Me.btnMainEmail.IsEnabled = False
            Me.btnSendEmail.IsEnabled = False
        End If
    End Sub

    Private Sub lvwPhoneNumbers_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles lvwPhoneNumbers.SelectionChanged

        If Me.lvwPhoneNumbers.SelectedItems.Count > 0 Then
            Me.btnEditPhone.IsEnabled = True
            Me.btnFaxPhone.IsEnabled = True
            Me.btnDeletePhone.IsEnabled = True
            Me.btnMainPhone.IsEnabled = True
        Else
            Me.btnEditPhone.IsEnabled = False
            Me.btnFaxPhone.IsEnabled = False
            Me.btnDeletePhone.IsEnabled = False
            Me.btnMainPhone.IsEnabled = False
        End If
    End Sub

    Private Sub lvwAddresses_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles lvwAddresses.SelectionChanged

        If Me.lvwAddresses.SelectedItems.Count > 0 Then
            Me.lblFullAddress.Text = CommonDataFunctions.GetAddressText(Me.lvwAddresses.SelectedItem.row.itemarray(0).ToString)
            Me.btnAddressEdit.IsEnabled = True
            Me.btnAddressDel.IsEnabled = True
            Me.btnCorrespondence.IsEnabled = True
            Me.btnInvoiceAddress.IsEnabled = True
            Me.btnAddressChangeToCo.IsEnabled = True
        Else
            Me.btnAddressEdit.IsEnabled = False
            Me.btnAddressDel.IsEnabled = False
            Me.btnCorrespondence.IsEnabled = False
            Me.btnInvoiceAddress.IsEnabled = False
            Me.btnAddressChangeToCo.IsEnabled = False
        End If
    End Sub

    Private Sub btnAddCase_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddCase.Click
        Dim frmAddNewCase As New frmAddNewCase
        With frmAddNewCase
            .CompanyId = GlobalCRM.CurrentCompanyID
            .ShowDialog()
            frmAddNewCase.ShowInTaskbar = True
        End With

        Dim myData As System.Data.DataTable

        If GlobalCRM.CurrentCompanyID = 0 Then
            myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(Me.CurrentCaseView, CaseTypes.Candidate))
        Else
            myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(Me.CurrentCaseView, CaseTypes.Company))
        End If

        If myData.Rows.Count > 0 Then
            'Display open cases
            Me.grdCases.ItemsSource = myData
        End If

        EventViewChanged(Nothing, New System.EventArgs)
        Me.RefreshEventList()

        frmAddNewCase = Nothing
    End Sub

    Private Sub btnGoTo_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnGoTo.Click
        DoSearch()
        loadTabCases = False
        loadTabAccounts = False
        loadTabCompany = False
        loadTabPeople = False
        loadTabEvent = False
        tabCase_Loaded(sender, e)
        Me.SelectActiveCase()
    End Sub

    Private Sub btnAddPersToComp2_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddPersToComp2.Click
        Dim frmAddPerson As New frmAddPerson
        Try

            frmAddPerson.ShowDialog()
            DataBinding.BindListView(Company.GetCorporateContacts(GlobalCRM.CurrentCompanyID), Me.lvwContacts)
            DataBinding.BindListView(Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.All), Me.lvwPeopleList)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainDisplay : btnAddPersToComp2_Click")
        Finally
            frmAddPerson = Nothing
        End Try
    End Sub

    Private Sub DoSearch()

        Dim lngSearchID As Long
        Dim strSearchResult As String
        Dim strName As String = String.Empty
        ' get search ID value

        Dim progressBar As frmProgressBar = Nothing
        ' open frmMainDisplay for selected event
        Try
            progressBar = New frmProgressBar()
            progressBar.TextToDisplay = "Dear " & GlobalCRM.CurrentConName & ", please wait while CRM loads ....."
            progressBar.Show()

            If Not IsNumeric(Me.txtGoto.Text) Then
                'Moditication starts
                ' - Do not just exit, inform the user that the id should be entered and not the name
                If radGotoCompany.IsChecked Then strName = radGotoCompany.Content
                If radGotoPerson.IsChecked Then strName = radGotoPerson.Content
                If radGotoCase.IsChecked Then strName = radGotoCase.Content

                CommonFuncs.DisplayMessage("Please enter Id of the " & strName, CommonDialog.CustomDialogIcons.Information, "Search ID")
                'Modification ends
                Exit Sub
            Else
                lngSearchID = Me.txtGoto.Text
            End If

            ' determine search type
            If Me.radGotoCase.IsChecked Then
                GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCase
                GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.eCase
            ElseIf Me.radGotoCompany.IsChecked Then
                GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCompany
                GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.eCompany
                'GlobalCRM.CurrentCompanyID = lngSearchID
            ElseIf Me.radGotoPerson.IsChecked Then
                GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.ePerson
                GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.ePerson
            End If

            ' run the search
            strSearchResult = CommonDataFunctions.IDSearch(lngSearchID, GlobalCRM.CurrentSearchType)
            If strSearchResult = "ok" Then

                'If Me.radGotoCase.IsChecked Then
                '    GlobalCRM.CurrentCaseID = lngSearchID
                'ElseIf Me.radGotoCompany.IsChecked Then
                '    GlobalCRM.CurrentCompanyID = lngSearchID
                'ElseIf Me.radGotoPerson.IsChecked Then
                '    GlobalCRM.CurrentCandidateID = lngSearchID
                'End If

                Me.LoadMainPage()

                'Me.frmMainDisplay_Loaded(Me, Nothing)
            Else
                MsgBox(strSearchResult)
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainDisplay : DoSearch")
        Finally
            progressBar.Close()
        End Try
    End Sub

    Private Sub ChangeCompanyPeopleView(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radCoCandidates.Checked, radCoContacts.Checked, radCoViewAll.Checked, radCoViewCat.Checked
        ' handle selection of View option (on People tab)
        Try
            Me.drpRoles.Visibility = System.Windows.Visibility.Hidden

            Select Case CType(CType(sender, RadioButton).Tag, Company.CompanyPeopleView)

                Case Company.CompanyPeopleView.All

                    DataBinding.BindListView(Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.All), Me.lvwPeopleList)

                Case Company.CompanyPeopleView.Candidates

                    DataBinding.BindListView(Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.Candidates), Me.lvwPeopleList)

                Case Company.CompanyPeopleView.Category

                    'DataBinding.BindListView(CommonSQL.GetCorporatePeople(GlobalCRM.CurrentCompanyID, CommonSQL.CompanyPeopleView.Category), Me.lvwPeopleList)
                    Me.drpRoles.Visibility = System.Windows.Visibility.Visible

                Case Company.CompanyPeopleView.Contacts

                    DataBinding.BindListView(Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.Contacts), Me.lvwPeopleList)


            End Select
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : ChangeCompanyPeopleView")
        Finally

        End Try
    End Sub

    Private Sub btnGotoParent_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnGotoParent.Click
        Try
            GlobalCRM.ResetGlobalVars()
            GlobalCRM.CurrentCandidateID = Me.lblDependOfId.Content

            Me.RemoveHandlers()
            _StopDuplicateLoad = False
            Me.frmMainDisplay_Loaded(Me.grdCases, New System.EventArgs)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : btnGotoParent_Click")
        Finally

        End Try
    End Sub

    Private Sub lvwPeopleList_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles lvwPeopleList.SelectionChanged
        Try
            If Me.lvwPeopleList.SelectedItems.Count > 0 Then

                GlobalCRM.CurrentCandidateID = Me.lvwPeopleList.SelectedItem.row.itemarray(0).ToString

                Me.ShowCandidateDetails(GlobalCRM.CurrentCandidateID)
                Me.lblCandidateName3.Text = GlobalCRM.CurrentCandidateName
                Me.lblCandidateId3.Text = GlobalCRM.CurrentCandidateID
                Me.LoadPhoneNumbers(GlobalCRM.CurrentCandidateID)

                Me.LoadEmailAddresses(GlobalCRM.CurrentCandidateID)

                Me.LoadAddresses(GlobalCRM.CurrentCandidateID)
                Me.lblFullAddress.Text = String.Empty
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : lvwPeopleList_SelectionChanged")
        Finally

        End Try
    End Sub

    Private Sub lvwContacts_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvwContacts.MouseDoubleClick
        Try
            If Me.lvwContacts.SelectedItems.Count > 0 Then

                'Select corresponding contact in list on people tab
                Me.lvwPeopleList.SelectedItems.Clear()

                Dim lvi As DataRowView

                For Each lvi In Me.lvwPeopleList.Items
                    If lvi.Row.ItemArray(0).ToString = Me.lvwContacts.SelectedItem.row.itemarray(0).ToString Then

                        'lvi.Selected = True
                        Exit For
                    End If
                Next

                Me.TabControl1.SelectedItem = Me.tabPeople
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : lvwContacts_MouseDoubleClick")
        Finally

        End Try

    End Sub

    Private Sub btnCoInvAddress_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCoInvAddress.Click
        ' set selected company address as Invoice address
        Try
            If Me.lvwCoAddresses.SelectedItems.Count = 0 Then
                CommonFuncs.DisplayMessage("No address selected.", CommonDialog.CustomDialogIcons.Information, "Address")
                Exit Sub
            End If

            If Company.SetCorrespOrInvAddress(Me.lvwCoAddresses.SelectedItem.row.itemarray(0).ToString, GlobalCRM.CurrentCompanyID, Me.lvwCoAddresses.SelectedItem.row.itemarray(3).ToString, Company.AddressLinkTypes.Invoice, Me.lvwCoAddresses.SelectedItem.row.itemarray(4).ToString) = True Then
                Me.LoadCompanyAddresses()
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : btnCoInvAddress_Click")
        Finally

        End Try
    End Sub

    Private Sub lvwEvents_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvwEvents.MouseDoubleClick
        Dim frmCompleteEvent As frmCompleteEvent
        Dim frmAddEvent As frmAddEvent
        Try


            Dim lngEventID As Integer


            If Me.lvwEvents.SelectedItems.Count = 0 OrElse Me.lvwEvents.Items.Count = 0 Then
                Exit Sub
            End If

            lngEventID = CLng(Me.lvwEvents.SelectedItem.row.itemarray(0).ToString)

            If CheckWhethetherTask(lngEventID) = True Then

                frmCompleteEvent = New frmCompleteEvent
                frmCompleteEvent.EventId = lngEventID
                frmCompleteEvent.ShowDialog()
                Me.RefreshEventList()

                If frmCompleteEvent.RepeatEvent Then

                    ' xxx you need to add code to ask for a repeat event

                End If


                If radEventAll.IsChecked = True Or radEventConsultant.IsChecked = True Then
                Else

                    If drpEventView.SelectedIndex = -1 OrElse drpEventView.SelectedValue < 1 Then
                        CommonFuncs.DisplayMessage("You must select a value from the dropdown above before you add a new event.", CommonDialog.CustomDialogIcons.Information, " ")
                        Exit Sub
                    End If
                    If GlobalCRM.ActionCancelled = False Then
                        If CommonFuncs.DisplayyesNoMessage("Do you want to add a new task to replace the one dismissed?", CommonDialog.CustomDialogIcons.Question, "Add new Task") = 1 Then
                            '                frmAddEvent.EventType = CType(tskInfo.LinkType, CommonSQL.EventTypes)
                            frmAddEvent = New frmAddEvent
                            frmAddEvent.radTask.IsChecked = True
                            btnAddEventToCase_Click(sender, e)

                        End If
                    Else
                        GlobalCRM.ActionCancelled = False
                    End If
                End If
            End If
        Catch ex As Exception
        Finally
            frmCompleteEvent = Nothing
            frmAddEvent = Nothing
        End Try

    End Sub

    Private Sub lvwEvents_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles lvwEvents.SelectionChanged
        Dim tsk As New TasksEvents
        Dim Cmn As New CommonFuncs
        Try

            If Me.lvwEvents.SelectedItems.Count > 0 Then

                Dim myEvent As TasksEvents.EventInfo = tsk.GetEvent(Me.lvwEvents.SelectedItem.row.itemarray(0).ToString)

                With myEvent
                    Me.lblMessage.Text = .Message
                    Me.lblEventId.Text = .EventId
                    Me.lblLinkedTo.Text = .LinkId
                    'Me.lblBooked1.Text =.
                    If .DateEntered = "00:00:00" Then
                        Me.lblBooked1.Content = String.Empty
                    Else
                        Me.lblBooked1.Content = Cmn.FormatDate(.DateEntered)
                    End If
                    If .DateScheduled = "00:00:00" Then
                        Me.lblScheduled1.Content = String.Empty
                    Else
                        Me.lblScheduled1.Content = Cmn.FormatDate(.DateScheduled)
                    End If
                    If .DateCompleted = "00:00:00" Then
                        Me.lblCompleted1.Content = String.Empty
                    Else
                        Me.lblCompleted1.Content = Cmn.FormatDate(.DateCompleted)
                    End If
                    Me.lblBooked2.Content = .EnteredBy
                    Me.lblScheduled2.Content = .ScheduledFor
                    Me.lblCompleted2.Content = .CompletedBy
                End With

            End If

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : lvwEvents_SelectionChanged")
        Finally
            tsk = Nothing
            Cmn = Nothing
        End Try

    End Sub

    Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnPrint.Click
        Try


            If lblEventId.Text = String.Empty Then
                CommonFuncs.DisplayMessage("Please select an event to print", CommonDialog.CustomDialogIcons.Information, "Please select")
                Exit Sub
            Else
                If MsgBox("Are you sure to print the selected event?", MsgBoxStyle.YesNo, "Print?") = MsgBoxResult.Yes Then
                    Dim CrystRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument
                    Dim Rpt As New EventPrintout
                    Dim dt As System.Data.DataTable = ReportCRM.GetReportData(ReportCRM.ReportType.EventPrint, CLng(lblEventId.Text))
                    Rpt.SetDataSource(dt)
                    If dt.Rows.Count > 0 Then
                        Rpt.SetDataSource(dt)
                        CrystRpt = Rpt
                        CrystRpt.PrintToPrinter(1, False, 0, 0)
                        'CrystRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.WordForWindows, "C:\Documents and Settings\v\Desktop\ss.doc")
                    Else
                        CommonFuncs.DisplayMessage("Contact IT", CommonDialog.CustomDialogIcons.Information, "")
                    End If
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : btnPrint_Click")
        End Try
    End Sub

    Private Sub btnEmailEvents_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEmailEvents.Click
        Dim sql As StringBuilder
        Dim dt As System.Data.DataTable
        Try
            If GlobalCRM.CurrentCaseID > 0 Then
                sql = New StringBuilder

                With sql
                    .Append("SELECT TOP 100 PERCENT Event_ID,  CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END AS EventDT, ")
                    .Append("   Event_Description,Event_Message, ISNULL(ConScheduled, ConEntered) AS con_name, ")
                    .Append("     CASE Event_Category WHEN 1 THEN '' WHEN 2 THEN 'Scheduled for ' + CONVERT(varchar(12), Event_DTScheduled, 103) ")
                    .Append("  WHEN 3 THEN 'Completed on ' + CONVERT(varchar(12), Event_DTCompleted, 103) END AS Category, ")
                    .Append("  CASE Event_LinkType WHEN 1 THEN 'Case' WHEN 2 THEN 'Person' WHEN 3 THEN 'Company' END AS LinkFor")
                    .Append(" FROM  dbo.V_Events WHERE  (Event_LinkID = " & GlobalCRM.CurrentCaseID & ") AND (Event_LinkType = 1)")
                    .Append(" ORDER BY CASE Event_Category WHEN 2 THEN Event_Dtscheduled WHEN 3 THEN Event_Dtcompleted ELSE Event_Dtentered END DESC")
                End With
                dt = CommonDataFunctions.GetSQLDatatable(sql.ToString)
                toexcel(dt)
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : btnEmailEvents_Click")
        Finally
            sql = Nothing
            dt = Nothing
        End Try
    End Sub

    Private Sub toexcel(ByVal dt As System.Data.DataTable)
        Dim oExcel As Object
        Dim oBook As Object
        Dim oSheet As Object
        Try


            'Start a new workbook in Excel.
            oExcel = CreateObject("Excel.Application")
            oBook = oExcel.Workbooks.Add
            'Add data to cells of the first worksheet in the new workbook.
            oSheet = oBook.Worksheets(1)
            oSheet.Range("A1").Value = "Case ID"
            oSheet.Range("B1").Value = "Event ID"
            oSheet.Range("C1").Value = "Event Date"
            oSheet.Range("D1").Value = "Description"
            oSheet.Range("E1").Value = "Event_Message"
            oSheet.Range("F1").Value = "Consultant name"
            oSheet.Range("G1").Value = "Category"
            oSheet.Range("H1").Value = "Link For"

            'oSheet.Range("J1").Value = "nationality"
            'oSheet.Range("K1").Value = "country"

            oSheet.Range("A1:B1:C1:D1:E1:F1:G1:H1").Font.Bold = True

            Dim DR As DataRow
            Dim i As Integer = 2
            For Each DR In dt.Rows
                oSheet.Range("A" & i).Value = GlobalCRM.CurrentCaseID
                oSheet.Range("B" & i).Value = DR.Item("Event_ID").ToString
                oSheet.Range("C" & i).Value = DR.Item("EventDT").ToString
                oSheet.Range("D" & i).Value = DR.Item("Event_Description").ToString
                oSheet.Range("E" & i).Value = DR.Item("Event_Message").ToString
                oSheet.Range("F" & i).Value = DR.Item("con_name").ToString
                oSheet.Range("G" & i).Value = DR.Item("Category").ToString
                oSheet.Range("H" & i).Value = DR.Item("LinkFor").ToString
                'oSheet.Range("G" & i).Value = DR.Item("Companyname").ToString
                'oSheet.Range("H" & i).Value = DR.Item("Product").ToString
                'oSheet.Range("I" & i).Value = DR.Item("ProductType").ToString
                'oSheet.Range("J" & i).Value = DR.Item("nationality").ToString
                'oSheet.Range("K" & i).Value = DR.Item("country").ToString
                i = i + 1
            Next
            'oSheet.Range("A2").Value = "Doe"
            'OSheet.Range("B2").Value = "John"

            'Save the Workbook and quit Excel.
            Dim DocFileName As String = "h:\Events_CaseID_" & GlobalCRM.CurrentCaseID & ".xls"
            'GlobalCRM.LocalAttachments.Attachments.Clear()
            'GlobalCRM.LocalAttachments.AddAttachment("Events for case no. " & GlobalCRM.CurrentCaseID, DocFileName)
            If File.Exists(DocFileName) = True Then
                File.Delete(DocFileName)
            End If
            oBook.SaveAs(DocFileName)
            'Me.close()
            If MsgBox("The Events are saved in H: " & vbCrLf & vbCrLf & "Path : " & DocFileName & vbCrLf & vbCrLf & "Would you like to open the file?", MsgBoxStyle.YesNo, "H:") = MsgBoxResult.Yes Then
                Dim Proc As New System.Diagnostics.Process

                With Proc.StartInfo
                    .Arguments = DocFileName
                    .UseShellExecute = True
                    .WindowStyle = ProcessWindowStyle.Maximized
                    '.WorkingDirectory = "C:\Program Files\Adobe\Reader 8.0\Acrobat\" '<----- Set Acrobat Install Path
                    .FileName = DocFileName '<----- Set Acrobat Exe Name
                End With

                Proc.Start()
                Proc.Close()
                Proc.Dispose()


                'Proc.StartInfo.WorkingDirectory = "H:\"
                'Proc.StartInfo.FileName = DocFileName
                'Proc.Start()
            End If
            oSheet = Nothing
            oBook = Nothing
            'oExcel.Quit()
            oExcel = Nothing
            GC.Collect()
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : toexcel")
        End Try
    End Sub

    Private Sub btnPrintAll_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnPrintAll.Click
        Try


            If MsgBox("Are you sure to print All the event?", MsgBoxStyle.YesNo, "Print?") = MsgBoxResult.Yes Then
                Dim CrystRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument
                Dim Rpt As New EventsDump
                Dim dt As System.Data.DataTable
                Dim strTxt As String = String.Empty
                If Me.radEventCase.IsChecked Then
                    dt = ReportCRM.SQL_EventPrintAll(EventView.CaseId, Me.drpEventView.SelectedValue)
                    strTxt = "Events For: Case No: " & Me.drpEventView.SelectedValue  ' & " (" & Me.Combo_Events_DataToView.Column(1) & ")"
                ElseIf Me.radEventPerson.IsChecked Then
                    dt = ReportCRM.SQL_EventPrintAll(EventView.Person, Me.drpEventView.SelectedValue)
                    strTxt = "Events For: Person: " & Me.drpEventView.Text ' & " (" & Me.drpEventView.Text & ")"
                ElseIf Me.radEventConsultant.IsChecked Then
                    dt = ReportCRM.SQL_EventPrintAll(EventView.Consultant, Me.drpEventView.SelectedValue)
                    strTxt = "Events For: Consultant: " & Me.drpEventView.Text & " (" & Me.drpEventView.Text & ")"
                ElseIf Me.radEventAll.IsChecked Then
                    ' - Testers wanted the defaulting for ALL. hence changed the defaulting as All.
                    'It was combined before
                    dt = ReportCRM.SQL_EventPrintAll(EventView.All, GlobalCRM.CurrentCompanyID)
                    'Me.EventSQL(EventView.All, Me.drpEventView.SelectedValue)
                    strTxt = "All associated Events "
                End If
                'dt = ReportCRM.GetReportData(ReportCRM.ReportType.EventsAllPrint)

                'Rpt.SetDataSource(dt)
                If Not dt Is Nothing Then
                    If dt.Rows.Count > 0 Then
                        Rpt.SetDataSource(dt)
                        CrystRpt = Rpt
                        CrystRpt.DataDefinition.FormulaFields("Description").Text = "'" & strTxt & "'"
                        CrystRpt.PrintToPrinter(1, False, 0, 0)
                        'CrystRpt.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.WordForWindows, "C:\Documents and Settings\v\Desktop\ss.doc")
                    Else
                        CommonFuncs.DisplayMessage("No Data to Print,Contact IT", CommonDialog.CustomDialogIcons.Information, "No Data")
                    End If
                Else
                    CommonFuncs.DisplayMessage("No Data to Print", CommonDialog.CustomDialogIcons.Information, "No Data")
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : btnPrintAll_Click")
        End Try
    End Sub

    Private Sub btnok_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnok.Click
        Dim opnMethod As Integer
        Try
            'IntPrint 0/1 = Create only, 2 = print, 3 = E-Mail, 4 = H: drive
            If Not grdInvoiceSummary.SelectedItem Is Nothing Then
                If drpMethod.SelectedIndex = -1 Then
                    CommonFuncs.DisplayMessage("Select the option (Print / Email / Save to H:) from the dropdownlist", CommonDialog.CustomDialogIcons.Information, "Please select an option")
                    Exit Sub
                Else
                    Select Case drpMethod.Text
                        Case "Print"
                            opnMethod = 1
                        Case "Email"
                            opnMethod = 2
                        Case "H: Drive"
                            opnMethod = 3
                    End Select

                End If

                GlobalCRM.CurrentInvoiceId = grdInvoiceSummary.SelectedItem.row.itemarray(0).ToString ', Xceed.Grid.CellRow).Cells(0).Value
                GlobalCRM.CurrentCaseID = grdInvoiceSummary.SelectedItem.row.itemarray(1).ToString 'CType(grdInvoiceSummary.SelectedItem, Xceed.Grid.CellRow).Cells(1).Value
                Dim l As Long = Accounts.Gblfunc_Print_Invoice(GlobalCRM.CurrentInvoiceId, opnMethod)
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub grdCaseSummary_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdCaseSummary.MouseDoubleClick
        ' use this to exclude a double click on the footer row
        Dim selectedRow As DataRowView = Me.grdCaseSummary.SelectedItem
        If Not selectedRow Is Nothing Then

            GlobalCRM.CurrentCaseID = CType(selectedRow(0), Long)
            CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonFuncs.DBIdTypes.CaseID)
            Dim formFinance As New frmFinances()
            formFinance.ShowDialog()

        End If

        'If Not IsNothing(Me.grdCaseSummary.CurrentRow) Then
        '    GlobalCRM.CurrentCaseID = CType(Me.grdCaseSummary.CurrentRow, Xceed.Grid.CellRow).Cells(0).Value
        '    CommonFunc.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonFunc.DBIdTypes.CaseID)
        '    frmFinances.ShowDialog()
        'End If
    End Sub

    Private Sub AccountDateRange_Changed(ByVal sender As Object, ByVal e As System.EventArgs) Handles radAccAll.Checked, radAccFrom.Checked, radAccLastMonth.Checked, radAccRange.Checked, radAccThisMonth.Checked

        Me.lblAccStart.Visibility = System.Windows.Visibility.Hidden
        Me.lblAccEnd.Visibility = System.Windows.Visibility.Hidden
        Me.txtAccStart.Visibility = System.Windows.Visibility.Hidden
        Me.txtAccEnd.Visibility = System.Windows.Visibility.Hidden
        'Me.AccStart.Visibility = Windows.Visibility.Hidden
        'Me.btnAccEnd.Visibility = Windows.Visibility.Hidden

        Select Case CInt(CType(sender, RadioButton).Tag)

            Case 1, 3, 4
                'Do nothing

            Case 2
                'From 
                Me.lblAccStart.Visibility = System.Windows.Visibility.Visible
                Me.txtAccStart.Visibility = System.Windows.Visibility.Visible
                'Me.btnAccStart.Visibility = Windows.Visibility.Visible

            Case 5
                Me.lblAccStart.Visibility = System.Windows.Visibility.Visible
                Me.txtAccStart.Visibility = System.Windows.Visibility.Visible
                'Me.btnAccStart.Visibility = Windows.Visibility.Visible

                Me.lblAccEnd.Visibility = System.Windows.Visibility.Visible
                Me.txtAccEnd.Visibility = System.Windows.Visibility.Visible
                'Me.btnAccEnd.Visibility = Windows.Visibility.Visible

        End Select

    End Sub

    Private Sub txtAccEnd_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles txtAccEnd.SelectedDateChanged
        Me.txtAccEnd.Text = (New CommonFuncs).FormatDate(Me.txtAccEnd.SelectedDate)
    End Sub

    Private Sub txtAccStart_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles txtAccStart.SelectedDateChanged
        Me.txtAccStart.Text = (New CommonFuncs).FormatDate(txtAccStart.SelectedDate)
    End Sub

    Private Sub btnCreateStatement_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCreateStatement.Click
        Dim StrFilename As String

        Dim StartDate As Date, EndDate As Date
        Dim Msg As String
        Dim SQL As StringBuilder
        Dim ClientName As String
        Dim ClientId As Long
        Dim SubsidiaryList As String
        Try

            'Me.Cursor = Cursors.WaitCursor
            Me.btnCreateStatement.IsEnabled = False

            If Me.radAccAll.IsChecked Then

                'No date range.
                Msg = " All"
                StartDate = CDate("1-Jan-1990 00:00:00")
                EndDate = Now.AddDays(1)

            ElseIf Me.radAccFrom.IsChecked Then

                If Not IsDate(Me.txtAccStart.Text) Then
                    CommonFuncs.DisplayMessage("Not a valid start date", CommonDialog.CustomDialogIcons.Information, "Error")
                    Me.txtAccStart.Focus()
                    Exit Sub
                End If

                If CDate(Me.txtAccStart.Text) > Now() Then
                    CommonFuncs.DisplayMessage("Start Date cannot be in the future", CommonDialog.CustomDialogIcons.Information, "Error")
                    Me.txtAccStart.Focus()
                    Exit Sub
                End If

                'Specific Day to present
                StartDate = CDate(Me.txtAccStart.Text) & " 00:00"
                EndDate = Now
                Msg = "From " & Me.txtAccStart.Text & " to " & (New CommonFuncs).FormatDate(Now)

            ElseIf Me.radAccRange.IsChecked Then

                'Date range

                If Not IsDate(Me.txtAccStart.Text) Then
                    CommonFuncs.DisplayMessage("Not a valid start date", CommonDialog.CustomDialogIcons.Information, "Error")
                    Me.txtAccStart.Focus()
                    Exit Sub
                End If

                If CDate(Me.txtAccStart.Text) > Now() Then
                    CommonFuncs.DisplayMessage("Start Date cannot be in the future", CommonDialog.CustomDialogIcons.Information, "Error")
                    Me.txtAccStart.Focus()
                    Exit Sub
                End If


                If Not IsDate(Me.txtAccEnd.Text) Then
                    CommonFuncs.DisplayMessage("Not a valid end date", CommonDialog.CustomDialogIcons.Information, "Error")
                    Me.txtAccEnd.Focus()
                    Exit Sub
                End If


                If CDate(Me.txtAccStart.Text) >= CDate(Me.txtAccEnd.Text) Then
                    CommonFuncs.DisplayMessage("That is not a valid date range, date till must be after date from", CommonDialog.CustomDialogIcons.Information, "Error")
                    Exit Sub
                End If

                StartDate = CDate(Me.txtAccStart.Text) & " 00:00"
                EndDate = CDate(Me.txtAccEnd.Text & " 23:59:59")
                Msg = "From " & Me.txtAccStart.Text & " to " & Me.txtAccEnd.Text

            ElseIf Me.radAccThisMonth.IsChecked Then
                'this month
                StartDate = "01-" & MonthName(Now.Month, True) & "-" & Now.Year & " 00:00"
                EndDate = Date.DaysInMonth(Now.Year, Now.Month) & "" & MonthName(Now.Month, True) & "-" & Now.Year & " 23:59"

                Msg = MonthName(Now.Month) & " " & Now.Year


            ElseIf Me.radAccLastMonth.IsChecked Then
                'Last Month

                If Now.Month = 1 Then
                    StartDate = "01-Dec-" & Now.Year - 1 & " 00:00"
                Else
                    StartDate = "01-" & MonthName(Now.Month - 1, True) & "-" & Now.Year & " 00:00"
                End If

                If Now.Month = 1 Then
                    EndDate = "31-Dec-" & Now.Year - 1 & " 00:00"
                Else
                    EndDate = "31-Dec-" & Now.Year & " 23:59"
                End If

                Msg = MonthName(StartDate.Month) & " " & StartDate.Year
            End If


            If GlobalCRM.CurrentCompanyID > 0 Then
                ClientName = "For company: " & GlobalCRM.CurrentCompanyName
                ClientId = GlobalCRM.CurrentCompanyID
            Else
                ClientName = "For client: " & GlobalCRM.CurrentCandidateName
                ClientId = GlobalCRM.CurrentCandidateID
            End If

            If Me.chkSubsidiary.IsChecked Then

                SubsidiaryList = CommonFuncs.ArrayToCSV(Company.SubsidiaryList(ClientId))


            Else
                SubsidiaryList = "(" & ClientId & ")"
            End If


            Dim myRep As New AccountStatement
            Dim c As CrystalDecisions.CrystalReports.Engine.ReportDocument

            myRep.SetDataSource(Accounts.GetAccountStatement(StartDate, EndDate, Msg, ClientName, GlobalCRM.CurrentCompanyID, ClientId, SubsidiaryList))

            c = myRep

            'Export report if Proforma

            'Select Case GlobalCRM.ReportCriteria.CurrentReport
            '    Case ReportCRM.ReportType.ProformaIndividual



            '        Dim c As CrystalDecisions.CrystalReports.Engine.ReportDocument

            '        c = Rpt

            '        c.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.WordForWindows, "c:\crap\exporttest.doc")
            '        'Me.CrystalReportViewer1.ExportReport()

            'End Select

            'myData.WriteXmlSchema("c:\crap\AccountStatement.xsd")

            Select Case Me.drpOutputTo.SelectedIndex

                Case 0
                    'Print
                    c.PrintToPrinter(1, True, 1, 1000)
                    '        DoCmd.OpenReport(stDocName, acNormal)

                    '        StrMess = "Statement printed for period: " & StrMess
                    '        If IsCo = 1 Then
                    '            Call GblFunc_Add_Event("Statement Created", StrMess, 1, LngID, 3)
                    '        Else
                    '            Call GblFunc_Add_Event("Statement Created", StrMess, 1, LngID, 2)
                    '        End If

                Case 1
                    'Preview
                    'With frmReportViewer
                    '    .MdiParent = frmMDIMain
                    '    .CrystalReportViewer1.ReportSource = myRep
                    '    frmReportViewer.Show()
                    'End With

                    '        DoCmd.OpenReport(stDocName, acPreview)
                    If MsgBox("The preview option is no longer supported in this version." & vbCrLf & vbCrLf & "Would you want to save it as excel instead ? ", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                        If Not Directory.Exists("H:\") Then
                            StrFilename = "C:\database\" & ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".xls"
                            MsgBox("There is no mapping to your personal area at the H: drive, so this report will be saved on the C: drive at " & StrFilename & ". Please create a mapping to the H: drive for the next time, or ask IT to do it for you, as it is a better place to store these files in the future.", , "Mapping Error")
                        Else
                            StrFilename = "H:\" & ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".xls"
                        End If

                        c.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.Excel, StrFilename)

                        Msg = "Statement created in Excel for period: " & Msg
                        Dim tskEvents As New TasksEvents
                        If GlobalCRM.CurrentCompanyID > 0 Then
                            tskEvents.GblFunc_Add_Event("Statement Created", Msg, TasksEvents.EventStatus.SingleEvent, ClientId, TasksEvents.EventTypes.EventCompany)
                        Else
                            tskEvents.GblFunc_Add_Event("Statement Created", Msg, TasksEvents.EventStatus.SingleEvent, ClientId, TasksEvents.EventTypes.EventPerson)
                        End If

                        If CRM.BusinessLayer.Documents.OpenFile(StrFilename) = False Then
                            CommonFuncs.DisplayMessage("The file should have been saved at: " & StrFilename & " but for some reason it could not be opened.", CommonDialog.CustomDialogIcons.Information, "Open Error")
                        End If

                    Else
                        Exit Sub
                    End If

                Case 2
                    'E-Mail as Word

                    If Not Directory.Exists("H:\") Then
                        StrFilename = "C:\database\" & ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".doc"
                        CommonFuncs.DisplayMessage("There is no mapping to your personal area at the H: drive, so this report will be saved on the C: drive at " & StrFilename & ". Please create a mapping to the H: drive for the next time, or ask IT to do it for you, as it is a better place to store these files in the future.", CommonDialog.CustomDialogIcons.Information, "Mapping Error")
                    Else
                        StrFilename = "H:\" & ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".doc"
                    End If

                    c.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.WordForWindows, StrFilename)
                    Dim formSendEmail As New frmSendEmail
                    formSendEmail.lstAttach.Items.Add(StrFilename)
                    'GlobalCRM.LocalAttachments.AddAttachment(ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".doc", StrFilename)

                    'frmSendEmail.MdiParent = frmMDIMain
                    formSendEmail.Show()

                Case 3
                    'File as Word

                    If Not Directory.Exists("H:\") Then
                        StrFilename = "C:\database\" & ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".doc"
                        CommonFuncs.DisplayMessage("There is no mapping to your personal area at the H: drive, so this report will be saved on the C: drive at " & StrFilename & ". Please create a mapping to the H: drive for the next time, or ask IT to do it for you, as it is a better place to store these files in the future.", CommonDialog.CustomDialogIcons.Information, "Mapping Error")
                    Else
                        StrFilename = "H:\" & ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".doc"
                    End If

                    c.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.WordForWindows, StrFilename)

                    Msg = "Statement created in Word for period: " & Msg
                    Dim tskEvents As New TasksEvents
                    If GlobalCRM.CurrentCompanyID > 0 Then
                        tskEvents.GblFunc_Add_Event("Statement Created", Msg, TasksEvents.EventStatus.SingleEvent, ClientId, TasksEvents.EventTypes.EventCompany)
                    Else
                        tskEvents.GblFunc_Add_Event("Statement Created", Msg, TasksEvents.EventStatus.SingleEvent, ClientId, TasksEvents.EventTypes.EventPerson)
                    End If

                    If CRM.BusinessLayer.Documents.OpenFile(StrFilename) = False Then
                        CommonFuncs.DisplayMessage("The file should have been saved at: " & StrFilename & " but for some reason it could not be opened.", CommonDialog.CustomDialogIcons.Information, "Open Error")
                    End If

                Case 4
                    'File as Excel

                    If Not Directory.Exists("H:\") Then
                        StrFilename = "C:\database\" & ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".xls"
                        CommonFuncs.DisplayMessage("There is no mapping to your personal area at the H: drive, so this report will be saved on the C: drive at " & StrFilename & ". Please create a mapping to the H: drive for the next time, or ask IT to do it for you, as it is a better place to store these files in the future.", CommonDialog.CustomDialogIcons.Information, "Mapping Error")
                    Else
                        StrFilename = "H:\" & ClientId & "_Statement_" & Format(Now(), "dd_MM_yy") & ".xls"
                    End If

                    c.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.Excel, StrFilename)

                    Msg = "Statement created in Excel for period: " & Msg
                    Dim tskEvents As New TasksEvents
                    If GlobalCRM.CurrentCompanyID > 0 Then
                        tskEvents.GblFunc_Add_Event("Statement Created", Msg, TasksEvents.EventStatus.SingleEvent, ClientId, TasksEvents.EventTypes.EventCompany)
                    Else
                        tskEvents.GblFunc_Add_Event("Statement Created", Msg, TasksEvents.EventStatus.SingleEvent, ClientId, TasksEvents.EventTypes.EventPerson)
                    End If

                    If CRM.BusinessLayer.Documents.OpenFile(StrFilename) = False Then
                        CommonFuncs.DisplayMessage("The file should have been saved at: " & StrFilename & " but for some reason it could not be opened.", CommonDialog.CustomDialogIcons.Information, "Open Error")
                    End If

            End Select
            Me.btnCreateStatement.IsEnabled = True

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay.btnCreateStatement_Click")
        Finally
            SQL = Nothing
        End Try
    End Sub

    Private Sub btnFundsOfStatement_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnFundsOfStatement.Click

        Dim StrName, StrDocName, StrName2 As String
        Dim StrWhere As String = String.Empty
        Dim SQL As New StringBuilder
        Dim myData As System.Data.DataTable
        Dim LngID As Long
        If GlobalCRM.CurrentCompanyID > 0 Then
            If Me.chkSubsidiary.IsChecked = True Then
                StrName = Me.lblCompanyName.Text
                StrName2 = "Including Subsidiaries"
                'StrWhere = " (V_Case.Case_CompanyID in " & GpID(Me.lblCompanyID.Text) & ")"
            Else
                StrName = Me.lblCompanyName.Text
                StrWhere = " (V_Case.Case_CompanyID = " & Me.lblCompanyID.Content & ")"
            End If
        Else
            StrName = Me.lblCompanyID.Content
            LngID = Me.lvwPeopleList.SelectedItems(0).Text
            StrWhere = " (V_Case.Case_CandidateID = " & Me.lvwPeopleList.SelectedItems(0).Text & ")"
        End If

        SQL.Append("SELECT V_Case.Case_ID, V_Case.Candidate, V_Case.Case_CandidateID, V_Case.Balance, V_Statement.ID, V_Statement.DT,")
        SQL.Append(" V_Statement.Type, V_Statement.Net, V_Statement.VAT, V_Statement.Gross, L_Products.Product_Name,")
        SQL.Append(" '" & (New CommonFuncs).SwapQuotes(StrName) & "' as Client, '" & (New CommonFuncs).SwapQuotes(StrName2) & "' as Subs")

        If Me.chkSubsidiary.IsChecked = True Then
            SQL.Append(", D_Company.Company_Name as Company")
        Else
            SQL.Append(",'' as Company")
        End If

        SQL.Append(" FROM V_Case LEFT OUTER JOIN")
        SQL.Append(" V_Statement ON V_Case.Case_ID = V_Statement.CASEID LEFT OUTER JOIN")
        SQL.Append(" L_Products ON V_Case.Case_ProductID = L_Products.Product_ID")


        If Me.chkSubsidiary.IsChecked = True Then
            SQL.Append(" LEFT OUTER JOIN D_Company on V_Case.Case_CompanyId = D_Company.Company_ID")
        End If

        SQL.Append(" WHERE (V_Case.Balance > 0.1) And " & StrWhere)

        myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

        StrDocName = "Rpt_StatementCasesOS"

        'Select Case Me.drpOutputTo

        '    Case 1
        '        'Print
        '        DoCmd.OpenReport(StrDocName, acNormal)

        '        If IsCo = 1 Then
        '            Call GblFunc_Add_Event("Statement Created", "Funds OS Statement printed", 1, LngID, 3)
        '        Else
        '            Call GblFunc_Add_Event("Funds OS Statement Created", "Funds OS Statement printed", 1, LngID, 2)
        '        End If

        '    Case 2
        '        'Preview
        '        DoCmd.OpenReport(StrDocName, acPreview)

        '    Case 3
        '        'E-Mail as Word
        '        DoCmd.OpenReport(StrDocName, acViewPreview)
        '        Reports(StrDocName).Visible = False

        '        StrFilename = "C:\database\" & LngID & "_Statement_" & Format(Now(), "dd_mm_yy") & ".doc"

        '        DoCmd.OutputTo(acReport, StrDocName, acFormatRTF, StrFilename, False)
        '        DoCmd.Close(acReport, StrDocName)

        '        StrSQL = "Insert Into Local_Attachments (Att_Name, Att_Filepath, Att_Temp)"
        '        StrSQL = StrSQL & " VALUES(""Statement " & Format(Now(), "dd-mm-yy") & """,""" & StrFilename & """,1 )"

        '        Dbs = CurrentDb

        '        Qry = Dbs.CreateQueryDef("", StrSQL)
        '        Qry.Execute()
        '        Qry = Nothing

        '        DoCmd.OpenForm("FM_SendMail")

        '        Form_Fm_SendMail.Txt_DataID = Me.Txt_Company_ID
        '        Form_Fm_SendMail.Txt_DataType = 3

        '        Form_Fm_SendMail.Combo_SystemMail.Enabled = False


        '    Case 4
        '        'File as Word

        '        StrFilename = "h:\" & LngID & "_Statement_" & Format(Now(), "dd_mm_yy") & ".doc"

        '        DoCmd.OpenReport(StrDocName, acViewPreview)
        '        Reports(StrDocName).Visible = False

        '        DoCmd.OutputTo(acReport, StrDocName, acFormatRTF, StrFilename, False)
        '        DoCmd.Close(acReport, StrDocName)

        '        oApp = CreateObject("Word.Application")
        '        oApp.Visible = True
        '        oApp.Documents.Open(StrFilename)

        '        oApp = Nothing

        '        If IsCo = 1 Then
        '            Call GblFunc_Add_Event("Statement Created", "Funds OS Statement saved to Word", 1, LngID, 3)
        '        Else
        '            Call GblFunc_Add_Event("Funds OS Statement Created", "Funds OS Statement saved to Word", 1, LngID, 2)
        '        End If

        '    Case 5
        '        'File as Excel
        '        DoCmd.OpenReport(StrDocName, acViewPreview)
        '        Reports(StrDocName).Visible = False

        '        StrFilename = "h:\" & LngID & "_Statement_" & Format(Now(), "dd_mm_yy") & ".xls"


        '        DoCmd.OutputTo(acReport, StrDocName, acFormatXLS, StrFilename, False)
        '        DoCmd.Close(acReport, StrDocName)

        '        oApp = CreateObject("Excel.Application")
        '        oApp.Visible = True
        '        oApp.Workbooks.Open(StrFilename)

        '        oApp = Nothing

        '        If IsCo = 1 Then
        '            Call GblFunc_Add_Event("Statement Created", "Funds OS Statement saved to Excel", 1, LngID, 3)
        '        Else
        '            Call GblFunc_Add_Event("Funds OS Statement Created", "Funds OS Statement saved to Excel", 1, LngID, 2)
        '        End If

        'End Select

        Exit Sub
    End Sub

    Private Sub btnAddEventToCase_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddEventToCase.Click
        Dim frmAddEvent As New frmAddEvent
        Try
            frmAddEvent.EventType = TasksEvents.EventTypes.EventCase
            frmAddEvent.LinkId = GlobalCRM.CurrentCaseID
            frmAddEvent.ShowDialog()
            Me.RefreshEventList()
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainDisplay : btnAddEventToCase_Click")
        Finally
            frmAddEvent = Nothing
        End Try
    End Sub

    Private Sub btnSend_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSend.Click
        Dim frmSendEmail As New frmSendEmail
        Select Case cmbEmailTo.Text.Trim.ToString
            Case "Blank"
                frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Blank
            Case "Candidate"
                frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Candidate
            Case "Contact"
                frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Contact
            Case "Both"
                frmSendEmail.iEmailType = CommonDataFunctions.EmailType.Both
        End Select
        'frmSendEmail.MdiParent = frmMDIMain
        frmSendEmail.Show()

    End Sub

    Private Sub btnPdf_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnPdf.Click

        'Dim TestPDF As New TestPDF
        'TestPDF.ShowDialog()
        Call CommonFuncs.DisplayMessage("This service has been withdrawn for a short while. IT has more information on this.", CommonDialog.CustomDialogIcons.Information, "Error")
    End Sub

#Region "Documents"

    Private Sub DocumentStore_Loaded()
        With Me.drpDocType
            .SelectedValuePath = "docreqtype_id"
            .DisplayMemberPath = "DocReqType_Name"
            .ItemsSource = CType(CRM.BusinessLayer.Documents.GetDocReqTypes, IListSource).GetList
            .SelectedIndex = -1
        End With

        DataBinding.BindListView(CRM.BusinessLayer.Documents.GetDocsRequiredForCase(GlobalCRM.CurrentCaseID), Me.lvwRequired)
        DataBinding.BindListView(CRM.BusinessLayer.Documents.GetCaseDocsInStore(GlobalCRM.CurrentCaseID), Me.lvwStored)
        'btnDefaults_Click(sender, e)
        With Me.cmbDocComments
            .DisplayMemberPath = "DocComment_Msg"
            .SelectedValuePath = "DocComment_Id"
            .ItemsSource = CType(CRM.BusinessLayer.Documents.DocCommentList, IListSource).GetList
            .SelectedIndex = -1
        End With
    End Sub

    Private Sub btnReceived_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnReceived.Click
        Dim Docs As New StringBuilder
        Dim Msg As New StringBuilder

        If Me.lvwRequired.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("No documents selected!", CommonDialog.CustomDialogIcons.Information, "Error")
            Exit Sub
        Else

            Dim lvi As DataRowView

            For Each lvi In Me.lvwRequired.SelectedItems

                If lvi.Row.ItemArray(4) <> "" Then
                    CommonFuncs.DisplayMessage("Some of those documents have already been received, you cannot receive them again.", CommonDialog.CustomDialogIcons.Information, "Error")
                    Exit Sub
                End If


                If Docs.ToString = String.Empty Then
                    Docs.Append("(")
                Else
                    Docs.Append(", ")
                End If

                Docs.Append(lvi.Row.ItemArray(0))
                Msg.Append(lvi.Row.ItemArray(2).ToString & " : " & lvi.Row.ItemArray(1).ToString & vbCrLf)


            Next

            Docs.Append(")")

        End If

        Msg.Insert(0, "The following docs have been marked as received" & vbCrLf & vbCrLf)

        If Not CRM.BusinessLayer.Documents.UpdateReceivedDate(GlobalCRM.CurrentConName, Docs.ToString, Msg.ToString, GlobalCRM.CurrentCaseID) Then
            Exit Sub
        End If

        'Call GblFunc_Populate_Case_Labels()

        DataBinding.BindListView(CRM.BusinessLayer.Documents.GetDocsRequiredForCase(GlobalCRM.CurrentCaseID), Me.lvwRequired)

    End Sub

    Private Sub btnDefaults_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDefaults.Click
        Dim ProductId As Long = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID).Productid
        Dim Msg As New StringBuilder
        Dim FirstCase As Integer
        Dim SQL As New StringBuilder

        If ProductId = 0 Then Exit Sub
        If CRM.BusinessLayer.Documents.CheckDefaultDocument(ProductId) = 0 Then
            'If DB.GetSQLScalar("Select DefDocReq_ID from D_DefDocReqs where DefDocReq_ProductID = " & ProductId) = 0 Then
            CommonFuncs.DisplayMessage("No default document requirements found for product " & Products.GetProductName(ProductId) & ". Please speak to an adminstrator", CommonDialog.CustomDialogIcons.Information, "Document")
            Exit Sub
        End If

        If CRM.BusinessLayer.Documents.GetDefaultDocument(GlobalCRM.CurrentCaseID) > 0 Then

            'If DB.GetSQLScalar(SQL.ToString) > 0 Then

            Msg.Append("Do you want to remove the existing requirements?" & vbCrLf)
            Msg.Append("(Received requirements will not be affected.)")

            If MsgBox(Msg.ToString, vbYesNo, "Add Defaults") = MsgBoxResult.Yes Then

                If Not CRM.BusinessLayer.Documents.DeleteDocRequirements(GlobalCRM.CurrentCaseID) Then
                    Exit Sub
                End If
            End If

        End If

        Msg.Insert(0, "Default doc reqs loaded onto case" & vbCrLf)

        'Check for previous initiated cases on this account

        If CRM.BusinessLayer.Documents.GetDefaultDocumentCount(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentCandidateID, GlobalCRM.CurrentCompanyID) = 0 Then

            'If DB.GetSQLScalar(SQL.ToString) = 0 Then
            FirstCase = 1
        Else
            FirstCase = 0
        End If

        'Add Document requirements
        'If Documents.CreateDocumentRequirements(GlobalCRM.CurrentCaseID, ProductId, GlobalCRM.CurrentCompanyID, Msg.ToString, GlobalCRM.CurrentConName, FirstCase) Then
        '    DataBinding.BindListView(Documents.GetDocsRequiredForCase(GlobalCRM.CurrentCaseID), Me.lvwRequired)
        'End If

        If CRM.BusinessLayer.Documents.CreateDocumentRequirementsLoad(GlobalCRM.CurrentCaseID, ProductId, GlobalCRM.CurrentCompanyID, Msg.ToString, GlobalCRM.CurrentConName, FirstCase) Then
            DataBinding.BindListView(CRM.BusinessLayer.Documents.GetDocsRequiredForCase(GlobalCRM.CurrentCaseID), Me.lvwRequired)
        End If

        'Call GblFunc_Populate_Case_Labels()

    End Sub

    'Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnClose.Click
    '    'Me.Close()
    'End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDelete.Click
        Dim Docs As New StringBuilder
        Dim Msg As New StringBuilder
        Dim Received As Boolean

        If Me.lvwRequired.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("No documents selected!", CommonDialog.CustomDialogIcons.Information, "Error")
            Exit Sub
        Else

            Dim lvi As DataRowView

            For Each lvi In Me.lvwRequired.SelectedItems

                If lvi.Row.ItemArray(4).ToString.Trim <> "" Then
                    Received = True
                End If

                If Docs.ToString = String.Empty Then
                    Docs.Append("(")
                Else
                    Docs.Append(", ")
                End If

                Docs.Append(lvi.Row.ItemArray(0).ToString)
                Msg.Append(lvi.Row.ItemArray(2).ToString & " : " & lvi.Row.ItemArray(1).ToString & vbCrLf)

            Next

            Docs.Append(")")

        End If

        If Received Then
            If MsgBox("Some of those documents have been marked as received, are you sure you want to delete them?", vbYesNo + vbQuestion, "Confirm") <> MsgBoxResult.Yes Then Exit Sub
        End If

        If MsgBox("The following document requirements have been selected for deletion, are you sure you wish to continue?" & vbCrLf & vbCrLf & Msg.ToString, vbYesNo + vbQuestion, "Confirm delete") <> MsgBoxResult.Yes Then Exit Sub


        If CRM.BusinessLayer.Documents.DeleteDocRequirementList(GlobalCRM.CurrentCaseID, Docs.ToString, Msg.ToString) Then
            DataBinding.BindListView(CRM.BusinessLayer.Documents.GetDocsRequiredForCase(GlobalCRM.CurrentCaseID), Me.lvwRequired)
        End If

        'Call GblFunc_Populate_Case_Labels()

    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAdd.Click
        If Me.txtDocName.Text.Trim = String.Empty Then
            CommonFuncs.DisplayMessage("Please provide a valid document name", CommonDialog.CustomDialogIcons.Information, "Error")
            Me.txtDocName.Focus()
            Exit Sub
        End If

        If Me.txtDocName.Text.Trim.Length > 200 Then
            CommonFuncs.DisplayMessage("Doc Name too long (Max 200 chars)", CommonDialog.CustomDialogIcons.Information, "Error")
            Me.txtDocName.Focus()
            Exit Sub
        End If

        If Me.drpDocType.SelectedIndex = -1 Then
            CommonFuncs.DisplayMessage("Please select a document type", CommonDialog.CustomDialogIcons.Information, "Error")
            Me.drpDocType.Focus()
            Exit Sub
        End If

        If CRM.BusinessLayer.Documents.AddNewDocReq(GlobalCRM.CurrentCaseID, Me.txtDocName.Text.Trim, Me.drpDocType.SelectedValue, Me.drpDocType.Text, GlobalCRM.CurrentConName) > 0 Then
            DataBinding.BindListView(CRM.BusinessLayer.Documents.GetDocsRequiredForCase(GlobalCRM.CurrentCaseID), Me.lvwRequired)
        End If

        'Call GblFunc_Populate_Case_Labels()

        Me.txtDocName.Text = String.Empty
        Me.drpDocType.SelectedIndex = -1
    End Sub

    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        Dim frmLoadToDocStore As New frmLoadToDocStore
        frmLoadToDocStore.ShowDialog()
        DataBinding.BindListView(CRM.BusinessLayer.Documents.GetCaseDocsInStore(GlobalCRM.CurrentCaseID), Me.lvwStored)

    End Sub

    Private Sub lvwStored_MouseDoubleClick1(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvwStored.MouseDoubleClick
        If Me.lvwStored.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("Please select a Doc Store.", CommonDialog.CustomDialogIcons.Information, "Doc Store")
            Exit Sub
        End If
        Dim frmDocumentList As New frmDocumentList
        frmDocumentList.DocStoreID = lvwStored.SelectedItem.row.itemarray(0)

        frmDocumentList.ShowDialog()

    End Sub

    Private Sub btnAddComment_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddComment.Click
        Dim Docs As New StringBuilder
        Dim Msg As New StringBuilder

        If Me.lvwRequired.SelectedItems.Count = 0 Then
            CommonFuncs.DisplayMessage("No documents selected!", CommonDialog.CustomDialogIcons.Information, "Error")
            Exit Sub
        ElseIf cmbDocComments.SelectedIndex = -1 Then
            CommonFuncs.DisplayMessage("No comment Selected!", CommonDialog.CustomDialogIcons.Information, "Error")
            Exit Sub
        Else

            Dim lvi As DataRowView

            For Each lvi In Me.lvwRequired.SelectedItems

                'If lvi.SubItems(4).Text.Trim <> "" Then
                '    MsgBox("Some of those documents have already been received, you cannot receive them again.", MsgBoxStyle.Exclamation, "Error")
                '    Exit Sub
                'End If
                If lvi.Row.ItemArray(4).ToString.Trim = String.Empty Then
                    CommonFuncs.DisplayMessage("Some of the selected documents have not been received yet, you cannot comment on them. Please unselect those items and add comment", CommonDialog.CustomDialogIcons.Information, "Error")
                    Exit Sub
                End If

                If Docs.ToString = String.Empty Then
                    Docs.Append("(")
                Else
                    Docs.Append(", ")
                End If

                Docs.Append(lvi.Row.ItemArray(0).ToString)
                Msg.Append(lvi.Row.ItemArray(2).ToString & " : " & lvi.Row.ItemArray(1).ToString & vbCrLf)


            Next

            Docs.Append(")")

        End If

        Msg.Insert(0, "The comment for the following document(s) has been uploaded" & vbCrLf & vbCrLf)
        If Not CRM.BusinessLayer.Documents.UpdateDocComments(Docs.ToString, cmbDocComments.SelectedValue, cmbDocComments.Text, GlobalCRM.CurrentCaseID) Then
            Exit Sub
        End If

        'Call GblFunc_Populate_Case_Labels()

        DataBinding.BindListView(CRM.BusinessLayer.Documents.GetDocsRequiredForCase(GlobalCRM.CurrentCaseID), Me.lvwRequired)

    End Sub

    'Private Sub TabControl1_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles TabControl1.SelectionChanged
    '    Dim selectedItem As TabItem = TabControl1.SelectedItem
    '    If selectedItem.Name = "tabDocuments" Then
    '        Me.DocumentStore_Loaded()
    '        selectedItem.Focus()
    '    End If

    'End Sub

#End Region
    Private Sub btnPrintSelDocs_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnPrintSelDocs.Click
        Dim dt As System.Data.DataTable
        Dim i As Integer
        Try

            If lvwStored.Items.Count = 0 Then
                Call CommonFuncs.DisplayMessage("There are documents configured for the case", CommonDialog.CustomDialogIcons.Information, "Error")
                'Exit Sub
            Else
                Dim lvi As DataRowView
                If CommonFuncs.DisplayyesNoMessage("Are you sure to print all selected documents?", CommonDialog.CustomDialogIcons.Question, "Print") = 1 Then
                    For Each lvi In Me.lvwStored.SelectedItems
                        dt = CRM.BusinessLayer.Documents.GetDocsInDocStore(lvi.Row.ItemArray(0).ToString.Trim())
                        If Not dt Is Nothing Then
                            If dt.Rows.Count > 0 Then

                                For i = 0 To dt.Rows.Count - 1
                                    CRM.BusinessLayer.Documents.PrintFile(dt.Rows(i).ItemArray(2).ToString)
                                Next


                            End If
                        End If
                    Next
                Else
                    Exit Sub
                End If

            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "btnPrintSelDocs_Click")
        Finally
            dt = Nothing
        End Try
    End Sub
    Private Sub btnPrintAllDocs_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnPrintAllDocs.Click
        Dim dt As System.Data.DataTable
        Dim i As Integer
        Try

            If lvwStored.Items.Count = 0 Then
                Call CommonFuncs.DisplayMessage("No documents for the case!", CommonDialog.CustomDialogIcons.Information, "Error")
                'Exit Sub
            Else
                Dim lvi As DataRowView
                If CommonFuncs.DisplayyesNoMessage("Are you sure to print all the documents?", CommonDialog.CustomDialogIcons.Question, "Print") = 1 Then
                    For Each lvi In Me.lvwStored.Items
                        dt = CRM.BusinessLayer.Documents.GetDocsInDocStore(lvi.Row.ItemArray(0).ToString.Trim())
                        If Not dt Is Nothing Then
                            If dt.Rows.Count > 0 Then

                                For i = 0 To dt.Rows.Count - 1
                                    CRM.BusinessLayer.Documents.PrintFile(dt.Rows(i).ItemArray(2).ToString)
                                Next


                            End If
                        End If
                    Next
                Else
                    Exit Sub
                End If

            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "btnPrintAllDocs_Click")
        Finally
            dt = Nothing
        End Try
    End Sub

    Private Sub tabDocuments_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles tabDocuments.GotFocus
        If loadTabDocs = False Then
            loadTabDocs = True
            If GlobalCRM.CurrentCaseID > 0 Then
                DocumentStore_Loaded()
            End If
        End If
    End Sub
    Private Sub MFB_Clicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles MFB1.Click, MFB2.Click, MFB3.Click, MFB4.Click, MFB5.Click, MFB6.Click, MFB7.Click, MFB8.Click, MFB9.Click

        Me.MFB_Execute(CType(sender, Button).Tag)

    End Sub
    Private Function MFB_Execute(ByVal ButtonPos As Integer) As Boolean

        Dim myCase As Cases.CaseInfo
        Dim GroupId As Integer
        Dim SQL As New StringBuilder
        Dim myData As System.Data.DataTable
        Dim frmBkFast As frmBookFastTrack
        'Dim frmAdv As frmAdverts
        Dim CommonSQL As New TasksEvents
        Try
            If GlobalCRM.CurrentCaseID = 0 Then
                Exit Function
            End If

            myCase = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID)

            GroupId = CommonDataFunctions.GblFunc_Get_Dataset(GlobalCRM.CurrentCaseID, 2)

            'We now have the group, position and stage, get the specific ref.

            With SQL

                .Append("SELECT I_MFB.MFB_ActionType, I_MFB.MFB_Argument ")

                .Append(" FROM I_MFB INNER JOIN I_MFBLinks ON I_MFB.MFB_ID = I_MFBLinks.MFBLink_MFBID")

                .Append(" WHERE (I_MFBLinks.MFBLink_GroupID = " & GroupId & ") ")

                .Append(" AND (I_MFBLinks.MFBLink_Position = " & ButtonPos & ") ")

                'Check for correct customer type
                If GlobalCRM.CurrentCompanyID = 0 Then
                    'Individual
                    .Append(" AND (I_MFBLInks.MFBLink_CustomerType = 0 Or I_MFBLInks.MFBLink_CustomerType = 1)")
                Else
                    'Company
                    .Append(" AND (I_MFBLInks.MFBLink_CustomerType = 0 Or I_MFBLInks.MFBLink_CustomerType = 2)")
                End If

                'Check System Version
                .Append(" AND (I_MFBLInks.MFBLink_SystemVersionActive  < = " & GlobalCRM.SysVersion & " )")
                .Append(" AND (I_MFBLInks.MFBLink_SystemVersionDisable > " & GlobalCRM.SysVersion & " OR I_MFBLinks.MFBLink_SystemVersionDisable = 0)")

                'Select based on current stage
                .Append(" AND (")
                .Append(" (I_MFBLinks.MFBLink_StageStart <= " & myCase.CaseStatusId & " AND I_MFBLinks.MFBLink_StageEnd > " & myCase.CaseStatusId & ")")
                .Append(" OR ")
                .Append(" (I_MFBLinks.MFBLink_StageStart = 0 AND I_MFBLinks.MFBLink_StageEnd > " & myCase.CaseStatusId & ")")
                .Append(" OR ")
                .Append(" (I_MFBLinks.MFBLink_StageStart <= " & myCase.CaseStatusId & " AND I_MFBLinks.MFBLink_StageEnd = 0)")
                .Append(" OR ")
                .Append(" (I_MFBLinks.MFBLink_StageStart = 0 AND I_MFBLinks.MFBLink_StageEnd = 0)")
                .Append(" )")
            End With

            myData = CommonDataFunctions.GetSQLDatatable(SQL.ToString)

            If IsNothing(myData) Then
                'Error State
                MsgBox("Didn't find button", MsgBoxStyle.Exclamation, "Error")
                Exit Function
            End If

            If myData.Rows.Count = 0 Then
                'Error State
                MsgBox("Didn't find button", MsgBoxStyle.Exclamation, "Error")
                Exit Function
            End If


            'Got what to do, now do it!

            Select Case myData.Rows(0).Item("MFB_ActionType")

                Case 1
                    'Open a form

                    'DoCmd.OpenForm(myData.Rows(0).Item("MFB_Argument"), acNormal)
                    'MsgBox("Not done yet!", MsgBoxStyle.Exclamation)

                    Select Case myData.Rows(0).Item("MFB_Argument").ToString
                        Case "FM_BookFastTrack"
                            frmBkFast = New frmBookFastTrack
                            frmBkFast.ShowDialog()
                        Case "frm_AdvertList"
                            'frmAdv = New frmAdverts
                            'frmAdv.ShowDialog()
                    End Select

                Case 301
                    'WP open the Advert list form for this case
                    'frmAdv = New frmAdverts
                    'frmAdv.ShowDialog()

                Case 302
                    'Open Assessing Auths Stock Letters

                    'Dim IntSLS As Integer, StrSLS As String, IntStage As Integer

                    'strSQL = "SELECT L_AssessingAuths.Assessingauth_SLSID"
                    'strSQL = strSQL & " FROM D_Case INNER JOIN"
                    'strSQL = strSQL & " D_Person ON D_Case.Case_CandidateID = D_Person.Person_ID INNER JOIN"
                    'strSQL = strSQL & " L_SkilledOcc ON D_Person.Person_SkilledOccID = L_SkilledOcc.SkilledOcc_ID INNER JOIN"
                    'strSQL = strSQL & " L_AssessingAuths ON L_SkilledOcc.SkilledOcc_AuthID = L_AssessingAuths.AssessingAuth_ID"
                    'strSQL = strSQL & " WHERE (D_Case.Case_ID = " & LngCaseID & ")"

                    'Rst = GSS(strSQL)

                    'If Rst.RecordCount = 0 Then
                    '    Rst.Close()
                    '    Call MsgBox("There are not Assessing Auth Stock Letters available for this Skilled Occupation")
                    '    Exit Function
                    'End If

                    'IntSLS = Rst.Fields("Assessingauth_SLSID")
                    'Rst.Close()

                    'strSQL = "Select SLS_Name from I_SL_StockLetterSets where SLS_ID = " & IntSLS

                    'Rst = GSS(strSQL)

                    'If Rst.RecordCount = 0 Then
                    '    StrSLS = IntSLS & " : Undefined"
                    'Else
                    '    StrSLS = IntSLS & " : " & Rst.Fields("SLS_Name")
                    'End If
                    'Rst.Close()

                    'If Me.Page_Company.Visible = True Then
                    '    IntCoType = 2
                    'Else
                    '    IntCoType = 1
                    'End If

                    'strSQL = "Select Case_StatusID from D_Case where Case_ID = " & Me.List_Case_Cases

                    'Rst = GblFunc_SQL_Select(strSQL, 2)

                    'If Rst.RecordCount = 0 Then Exit Function

                    'IntStage = Rst.Fields("Case_StatusID")
                    'Rst.Close()

                    'DoCmd.OpenForm("Fm_Stockletters")

                    'strSQL = " SELECT D_LetterPacks.LetterPack_ID, D_LetterPacks.LetterPack_Name"
                    'strSQL = strSQL & " FROM I_SL_SLSLink INNER JOIN D_LetterPacks ON I_SL_SLSLink.SLSLink_LetterPackID = D_LetterPacks.LetterPack_ID"

                    'strSQL = strSQL & " WHERE (I_SL_SLSLink.SLSLink_CustomerType = " & IntCoType & " or I_SL_SLSLink.SLSLink_CustomerType = 0)"
                    'strSQL = strSQL & " AND (I_SL_SLSLink.SLSLink_StageStart <= " & IntStage & ")"
                    'strSQL = strSQL & " AND (I_SL_SLSLink.SLSLink_StageEnd > " & IntStage & ")"
                    'strSQL = strSQL & " AND (I_SL_SLSLink.SLSLink_SLSID = " & IntSLS & ")"

                    'strSQL = strSQL & "ORDER BY I_SL_SLSLink.SLSLink_Order"

                    'Call GblFunc_Populate_List(strSQL, "FM_Stockletters_LetterpackList", Form_Fm_StockLetters.List_Letterpacks)
                    'Form_Fm_StockLetters.Txt_SLSTitle = StrSLS
                    MsgBox("Not done yet!", MsgBoxStyle.Exclamation, "Oops")

                Case 303
                    'Toggle On hold Status
                    Dim myReason As String
                    Dim dt As System.Data.DataTable
                    Dim Holdcase As Integer
                    Dim HoldToDate As String
                    dt = CommonDataFunctions.GetSQLDatatable("select Case_ActiveStatus,case_DTHoldTo from d_case where case_id = " & GlobalCRM.CurrentCaseID)
                    If Not dt Is Nothing Then
                        If dt.Rows.Count > 0 Then
                            Holdcase = CInt(dt.Rows(0).Item("Case_ActiveStatus").ToString)
                            If dt.Rows(0).Item("case_DTHoldTo").ToString.Trim <> "" Then
                                HoldToDate = dt.Rows(0).Item("case_DTHoldTo").ToString
                            Else
                                HoldToDate = "x"
                            End If
                        End If
                    End If
                    If HoldToDate <> "x" And myCase.OnHold = False Then
                        MsgBox("The case has been put on hold until " & HoldToDate & ". A case could be put on hold only once.")
                        Exit Select
                    End If
                    If Not myCase.OnHold Then
                        Dim frmCaseHold As New frmCaseHold
                        frmCaseHold.ShowDialog()
                        frmCaseHold = Nothing
                        myReason = GlobalCRM.HoldReason
                        'myReason = InputBox("Please enter reason for placing on hold", "Place Case On hold")

                        If myReason.Trim = "" Then
                            MsgBox("Action cancelled", MsgBoxStyle.Exclamation, "Cancelled")
                            Exit Function
                        End If
                        'show the email to be sent screen
                        Dim balance As Double = 0.0
                        'Check case balance
                        Dim objBal As Object = CommonDataFunctions.GetSQLScalar("SELECT  Balance FROM dbo.V_Case  WHERE (Case_ID = " & myCase.CaseId & ")")
                        If Not objBal Is Nothing Then
                            If objBal.ToString <> "" Then
                                balance = CDbl(objBal.ToString)
                            End If
                        End If
                        If balance > 0 Then
                            Dim TemplateID As Integer
                            'Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
                            'TemplateID = CType(configurationAppSettings.GetValue("EmailTemplate_CaseHold", GetType(System.Int16)), Integer)


                            TemplateID = GetCustomizationValue("CaseHold")
                            If TemplateID > 0 Then

                                If myCase.CompanyId = 0 Then
                                    If SendEmail_Hold(myCase.CaseId, myCase.CandidateId, TemplateID, GlobalCRM.CurrentConID) = False Then
                                        Exit Function
                                    End If
                                ElseIf myCase.CompanyId > 0 Then
                                    If SendEmail_Hold(myCase.CaseId, myCase.Contactid, TemplateID, GlobalCRM.CurrentConID) = False Then
                                        Exit Function
                                    End If
                                End If
                            End If
                        End If

                        myReason = "Case placed On Hold, reason below" & vbCrLf & vbCrLf & myReason.Trim

                        If Not CommonDataFunctions.ExecuteSQL("Update D_Case Set Case_ActiveStatus = 1,case_DTHoldTo = '" & GlobalCRM.HoldDate & "' Where Case_ID = " & GlobalCRM.CurrentCaseID) Then
                            Exit Function
                        End If

                        CommonSQL.GblFunc_Add_Event("Case placed on Hold", myReason, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, CommonSQL.EventTypes.EventCase)

                        'If MsgBox("Add a task?", vbYesNo, "Case placed on Hold") = MsgBoxResult.Yes Then
                        'Call Btn_Case_AddEvent_Click()
                        'Form_Fm_AddEvent.Frm_Event_Type = 2
                        'Call Form_Fm_AddEvent.Frm_Event_Type_AfterUpdate()
                        'End If

                    Else
                        If Not CommonDataFunctions.ExecuteSQL("Update D_Case Set Case_ActiveStatus = 0,case_dtholdto = null Where Case_ID = " & GlobalCRM.CurrentCaseID) Then
                            Exit Function
                        End If

                        CommonSQL.GblFunc_Add_Event("Hold Cancelled", "Hold Cancelled", TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase)
                    End If

                    'Me.Txt_Case_Status.SetFocus()
                    'Me.List_Case_Cases.Requery()
                    'Call GblFunc_Populate_Case()
                    Me.SelectedCaseChanged()
                    Me.DisplayNewCaseStatus(True)

                Case Else
                    MsgBox("No action defined for this button")

            End Select

            Return True
        Catch exc As Exception
            CommonFuncs.ErrorHandler(exc, "frmMainDisplay.mfb_Execute")
        Finally
            If Not frmBkFast Is Nothing Then
                frmBkFast.Close()
                frmBkFast = Nothing
            End If
        End Try

    End Function
    Public Shared Function SendEmail_Hold(ByVal caseid As Long, ByVal personid As Long, ByVal Templateid As Integer, ByVal currentCon As Long) As Boolean
        'Dim db As New CRM.BusinessLayer.CommonDataFunctions
        Dim tsk As TasksEvents
        Dim cmn As CommonFuncs
        Try
            Dim sqlbldr As New StringBuilder
            Dim EmailFrom As String = ""
            Dim strTemp As String
            Dim Attach As GlobalCRM.LocalAttachments.LocalAttachment
            Dim DocStoreId As Long
            Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader

            Dim attachnames As StringBuilder
            'Select - case for appropriate case advancement
            If Templateid <> 0 Then
                'Dim EmailFrom As String
                Dim EmailTo As String
                EmailFrom = "client-services@crmvisas.com"
                'If EmailFrom = "" Then
                '    sqlbldr.Append("Select Con_EMail from L_Consultant where Con_ID = " & currentCon)
                '    EmailFrom = DB.GetSQLScalar(sqlbldr.ToString)
                'End If
                'If EmailFrom Is Nothing Then
                '    MsgBox("Your email id is not updated in the database." & vbCrLf & "Please contact IT", MsgBoxStyle.Critical, "Email Not sent")
                '    Exit Function

                'End If

                Dim DataType As Integer
                Dim DataID As Long
                If GlobalCRM.CurrentCompanyID = 0 Then
                    DataType = 1
                    DataID = caseid
                    sqlbldr = New StringBuilder
                    sqlbldr.Append("Select EmailAddress_Address from D_EmailAddress where EmailAddress_personID = " & personid)
                    EmailTo = CommonDataFunctions.GetSQLScalar(sqlbldr.ToString)
                    If EmailTo Is Nothing Then
                        MsgBox("The Email address of the client is not found in the system. Hence email has not been sent", MsgBoxStyle.OkOnly, "Email Not sent")
                        Exit Function
                    End If
                Else
                    DataType = 3
                    DataID = GlobalCRM.CurrentCompanyID
                    'Fetch the company's contact and send email to associated ocntact and not the candidate
                    sqlbldr = New StringBuilder
                    sqlbldr.Append("SELECT     dbo.D_EmailAddress.EMailAddress_Address FROM   dbo.D_Case INNER JOIN   dbo.D_EmailAddress ON dbo.D_Case.Case_ContactID = dbo.D_EmailAddress.EMailAddress_PersonID WHERE     (dbo.D_Case.Case_ID = " & GlobalCRM.CurrentCaseID & ")")
                    EmailTo = CommonDataFunctions.GetSQLScalar(sqlbldr.ToString)
                    If EmailTo Is Nothing Then
                        MsgBox("The Email address of the client is not found in the system. Hence email has not been sent", MsgBoxStyle.OkOnly, "Email Not sent")
                        Exit Function
                    End If
                End If
                Dim dt As System.Data.DataTable

                Dim myTemplate As Letters.EmailTemplate
                myTemplate = Letters.GetEmailTemplate(Templateid)
                'Dim StrSQL As String

                Dim StrSQLBookmarks As String = ""
                Dim intCount As Integer = 1
                Dim txtfile As String = System.IO.Path.GetTempPath & "CRMTemp\sample.txt"
                Directory.CreateDirectory(System.IO.Path.GetTempPath & "CRMTemp")

                Dim oWrite As System.IO.StreamWriter
                oWrite = File.CreateText(System.IO.Path.GetTempPath & "CRMTemp\sample.txt")
                oWrite.Write(myTemplate.Body)
                oWrite.Close()

                Dim oRead As System.IO.StreamReader
                Dim LineIn As String
                Dim strNew() As String
                Dim strnew1() As String
                Dim i As Integer
                Dim c As New Microsoft.VisualBasic.Collection
                Dim cData As Microsoft.VisualBasic.Collection
                Dim cIndex As New Microsoft.VisualBasic.Collection
                Dim bln As Boolean
                oRead = IO.File.OpenText(txtfile)
                While oRead.Peek <> -1
                    LineIn = oRead.ReadLine()
                    strNew = Split(LineIn, "[")
                    For i = 0 To strNew.Length - 1
                        strnew1 = Split(strNew(i).ToString, "]")
                        If strnew1.Length > 1 Then
                            'StrSQLBookmarks = strnew1(0).ToString
                            StrSQLBookmarks = StrSQLBookmarks & "'" & strnew1(0).ToString & "',"
                            If cIndex.Contains(strnew1(0).ToString) = False Then
                                cIndex.Add(i, strnew1(0).ToString)
                                bln = True
                            End If
                            If bln Then
                                c.Add(strnew1(0).ToString)
                            End If
                            bln = False
                        End If
                    Next
                End While
                oRead.Close()

                StrSQLBookmarks = Left(StrSQLBookmarks, (Len(StrSQLBookmarks) - 1))
                StrSQLBookmarks = "(" & StrSQLBookmarks & ")"

                Dim sql1 As New StringBuilder
                With sql1
                    .Append("SELECT BookMark_Text as BMName")
                    .Append(" FROM I_SL_Bookmarks")
                    .Append(" WHERE Bookmark_Text in " & StrSQLBookmarks & "")
                    '.Append(" AND Bookmark_VersionID <= " & 1)
                    .Append(" GROUP BY BookMark_Text")
                End With
                dt = CommonDataFunctions.GetSQLDatatable(sql1.ToString)
                If Not dt Is Nothing Then
                    If dt.Rows.Count > 0 Then
                        Dim StrBMData As String = ""
                        cData = New Microsoft.VisualBasic.Collection
                        For i = 0 To dt.Rows.Count - 1
                            ' So we can monitor value
                            strTemp = dt.Rows(i).Item("BMName")
                            If dt.Rows(i).Item("BMName") <> "" Then
                                If GlobalCRM.CurrentCompanyID <> 0 Then
                                    If dt.Rows(i).Item("BMName") = "CandidateDearName" Then
                                        StrBMData = Letters.Gblfunc_Get_BookmarkData("ContactDearName", DataID, DataType)
                                        cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                    Else
                                        DataType = 1
                                        DataID = caseid
                                        StrBMData = Letters.Gblfunc_Get_BookmarkData(dt.Rows(i).Item("BMName"), DataID, DataType)
                                        cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                    End If
                                Else
                                    StrBMData = Letters.Gblfunc_Get_BookmarkData(dt.Rows(i).Item("BMName"), DataID, DataType)
                                    cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                End If
                            End If
                            If StrBMData = "EmailError_IT_Contact" Then
                                System.IO.File.Delete(txtfile)
                                Directory.Delete(System.IO.Path.GetTempPath & "CRMTemp\")
                                Exit Function
                            End If
                        Next
                    End If
                End If
                oRead = IO.File.OpenText(txtfile)
                Dim strRep As String = oRead.ReadToEnd
                oRead.Close()
                Dim OpToEmail As String
                For i = 1 To cData.Count
                    If OpToEmail = "" Then
                        OpToEmail = strRep.Replace("[" & c.Item(i) & "]", cData.Item(c.Item(i)))
                    Else
                        OpToEmail = OpToEmail.Replace("[" & c.Item(i) & "]", cData.Item(c.Item(i)))
                    End If
                Next
                'Dim subj As String = "Global Visas Case Update"
                Dim Signature As String = CommonDataFunctions.GblFunc_Get_Sigfile(GetCustomizationValue("ConID" & GetBranchID(GlobalCRM.CurrentConID)), False)
                OpToEmail = OpToEmail & vbCrLf & Signature
                'EMAILBCCSTRING
                EMAILBODYSTRING = OpToEmail
                EMAILSUBJECTSTRING = GlobalCRM.subj
                EMAILFROMSTRING = EmailFrom
                EMAILTOSTRING = EmailTo
                Dim frmEmailCaseNavigation As New frmEmailCaseNavigation
                frmEmailCaseNavigation.ShowDialog()

                If frmEmailCaseNavigation.lstAttach.Items.Count = 0 Then
                    GlobalCRM.LocalAttachments.Attachments.Clear()
                ElseIf frmEmailCaseNavigation.lstAttach.Items.Count = 1 And frmEmailCaseNavigation.lstAttach.Items(0).content.ToString = "lstAttach" Then
                    GlobalCRM.LocalAttachments.Attachments.Clear()
                End If
                frmEmailCaseNavigation = Nothing
                If blnAmendDataBeforeEmail Then
                    Exit Function
                Else
                    attachnames = New StringBuilder
                    If GlobalCRM.LocalAttachments.Attachments.Count > 0 Then
                        'Add files to Docstore then pass Docstore ID to the mail engine

                        DocStoreId = Letters.GblFunc_Create_DocStore("Files E-Mailed", "Documents E-Mailed", GlobalCRM.CurrentCaseID, 1)

                        For Each Attach In GlobalCRM.LocalAttachments.Attachments

                            If Letters.GblFunc_Add_FileToStore(Attach.Filepath, Strings.Left(Attach.Name, 99), DocStoreId) = 0 Then
                                MsgBox("Couldn't find attachment file, send failed", MsgBoxStyle.Critical)
                                Exit Function
                            End If

                            attachnames.Append(Attach.Filepath)
                            attachnames.Append(vbCrLf)
                        Next

                    End If
                    Dim Success As Integer = Letters.GblFunc_Send_MailEngine(EMAILTOSTRING, EMAILFROMSTRING, EMAILSUBJECTSTRING, EMAILBODYSTRING, , EMAILBCCSTRING, DocStoreId)

                    Dim Msg As New StringBuilder
                    With Msg
                        .Append("Email Sent" & vbCrLf & vbCrLf & "To: " & EmailTo)

                        .Append(vbCrLf & vbCrLf & "Sent via mail engine")
                        .Append(vbCrLf & "Subject: " & GlobalCRM.subj)
                        .Append(vbCrLf & "Attachments : " & attachnames.ToString)
                        .Append(vbCrLf & "Message: " & vbCrLf & vbCrLf & EMAILBODYSTRING)
                    End With
                    EMAILSUBJECTSTRING = ""
                    EMAILBODYSTRING = ""
                    EMAILBCCSTRING = ""
                    tsk = New TasksEvents
                    tsk.GblFunc_Add_Event("Send Email", Msg.ToString, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , 1)
                    If Success = 1 Then
                        'MsgBox("Email has been sent to the client successfully.", MsgBoxStyle.Information, "Success")
                    End If
                    GlobalCRM.LocalAttachments.Attachments.Clear()
                    System.IO.File.Delete(txtfile)
                    cmn = New CommonFuncs
                    cmn.ForceDeleteTempDir()
                    Return True
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "CommonFunc.SendEmailToClient", True)
        Finally
            tsk = Nothing
            cmn = Nothing
        End Try
    End Function


    Private Sub tabAccount_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles tabAccount.GotFocus
        Try
            If loadTabAccounts = False Then
                loadTabAccounts = True
                If GlobalCRM.CurrentCompanyID = 0 Then


                    DataBinding.BindListView(Accounts.CaseSummary(GlobalCRM.CurrentCandidateID, Accounts.AccountTypes.Individual), Me.grdCaseSummary)


                    DataBinding.BindListView(Accounts.InvoiceSummary(GlobalCRM.CurrentCandidateID, Accounts.AccountTypes.Individual), Me.grdInvoiceSummary)

                Else
                    DataBinding.BindListView(Accounts.CaseSummary(GlobalCRM.CurrentCompanyID, Accounts.AccountTypes.Corporate), Me.grdCaseSummary)

                    'accountInvoiceSummary = Accounts.InvoiceSummary(GlobalCRM.CurrentCandidateID, Accounts.AccountTypes.Corporate)
                    DataBinding.BindListView(Accounts.InvoiceSummary(GlobalCRM.CurrentCompanyID, Accounts.AccountTypes.Corporate), Me.grdInvoiceSummary)

                End If


                Dim myAccountsSummary As Accounts.AccountsSummary

                myAccountsSummary = Accounts.GetAccountsSummary(GlobalCRM.CurrentCaseID)
                Me.lblBalanceLarge.Content = Format(myAccountsSummary.Balance, m_strCurrencyChar & "0.00")
                Me.radAccAll.IsChecked = True
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "tabAccount_GotFocus")
        End Try
    End Sub

    Private Sub tabPeople_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles tabPeople.GotFocus
        Try
            If loadTabPeople = False Then
                loadTabPeople = True

                DataBinding.BindListView(Company.GetCorporatePeople(GlobalCRM.CurrentCompanyID, Company.CompanyPeopleView.All), Me.lvwPeopleList)
                If GlobalCRM.CurrentCandidateID = 0 Then
                    If lvwPeopleList.Items.Count > 0 Then
                        'GlobalCRM.CurrentCandidateID = lvwPeopleList.Items(0).row.itemarray(0).ToString
                        lvwPeopleList.SelectedIndex = 0
                    End If
                End If

                If GlobalCRM.CurrentCandidateID > 0 Then

                    Me.LoadPhoneNumbers(GlobalCRM.CurrentCandidateID)
                    Me.LoadEmailAddresses(GlobalCRM.CurrentCandidateID)
                    Me.LoadAddresses(GlobalCRM.CurrentCandidateID)

                Else

                    Me.lvwEmailAddress.ItemsSource = Nothing
                    Me.lvwEmailAddress.Items.Clear()
                    Me.lvwPhoneNumbers.ItemsSource = Nothing
                    Me.lvwPhoneNumbers.Items.Clear()
                    Me.lvwAddresses.ItemsSource = Nothing
                    Me.lvwAddresses.Items.Clear()
                End If
                If GlobalCRM.CurrentCompanyID = 0 Then
                    Me.lvwPeopleList.Visibility = System.Windows.Visibility.Hidden
                    Me.btnAddPersToComp2.Visibility = System.Windows.Visibility.Hidden
                    Me.grpRoleView.Visibility = System.Windows.Visibility.Hidden
                Else

                    If Not Me.lvwPeopleList.SelectedIndex = -1 Then
                        Me.lvwPeopleList.SelectedIndex = 0
                    End If
                    lvwPeopleList.SelectedItem = 0

                    Me.lvwPeopleList.Visibility = System.Windows.Visibility.Visible
                    Me.btnAddPersToComp2.Visibility = System.Windows.Visibility.Visible
                    Me.grpRoleView.Visibility = System.Windows.Visibility.Visible
                    With Me.drpRoles
                        .DisplayMemberPath = "role_name"
                        .SelectedValuePath = "role_id"
                        .ItemsSource = CType(Company.CompanyRoleList, IListSource).GetList
                    End With
                    AddHandler drpRoles.SelectionChanged, AddressOf drpRoles_SelectionChanged
                    Me.grpRoleView.Visibility = System.Windows.Visibility.Visible
                    'tabPeopless()
                    If GlobalCRM.CurrentCandidateID > 0 Then
                        'Dim itemTable As DataTable
                        'itemTable = CRM.BusinessLayer.People.GetDependants(CRM.BusinessLayer.GlobalCRM.CurrentCandidateID)
                        DataBinding.BindListView(CRM.BusinessLayer.People.GetDependants(CRM.BusinessLayer.GlobalCRM.CurrentCandidateID), Me.lvwDepend)
                    End If
                End If
                Me.ShowCandidateDetails(GlobalCRM.CurrentCandidateID)
                If GlobalCRM.CurrentCompanyID > 0 Then
                    lvwPeopleList.Visibility = System.Windows.Visibility.Visible
                    btnAddPersToComp2.Visibility = System.Windows.Visibility.Visible
                ElseIf GlobalCRM.CurrentCompanyID = 0 Then
                    lvwPeopleList.Visibility = System.Windows.Visibility.Hidden
                    btnAddPersToComp2.Visibility = System.Windows.Visibility.Hidden
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "tabPeople_GotFocus")
        End Try
    End Sub

    Private Sub tabEvent_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles tabEvent.GotFocus
        Try
            If loadTabEvent = False Then
                loadTabEvent = True

                If GlobalCRM.CurrentCompanyID = 0 Then
                    radEventCompany.IsEnabled = False
                Else
                    radEventCompany.IsEnabled = True
                End If

                If GlobalCRM.CurrentCaseID > 0 Then
                    'All.
                    Me.radEventAll.IsChecked = True
                    Me.btnAddEventToCase.Content = "Add Event to Case"

                    Me.EventViewChanged(Me.radEventAll, New EventArgs)
                ElseIf GlobalCRM.CurrentCandidateID > 0 Then
                    Me.radEventPerson.IsChecked = True
                    Me.btnAddEventToCase.Content = "Add Event to Person"

                    Me.EventViewChanged(Me.radEventPerson, New EventArgs)
                    Me.drpEventView.SelectedValue = GlobalCRM.CurrentCandidateID
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "tabEvent_GotFocus")
        End Try
    End Sub

    Private Sub tabCompany_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles tabCompany.GotFocus

        Dim subSidiaryList, corporateContacts As System.Data.DataTable ' , corporatePeople As DataTable
        Try
            If loadTabCompany = False Then
                loadTabCompany = True

                Me.LoadCompanyInfo()
                subSidiaryList = CommonDataFunctions.SubsidiaryList(GlobalCRM.CurrentCompanyID)
                DataBinding.BindListView(subSidiaryList, Me.lvwSubsidiary)


                corporateContacts = Company.GetCorporateContacts(GlobalCRM.CurrentCompanyID)
                DataBinding.BindListView(corporateContacts, Me.lvwContacts)

                Me.LoadCompanyAddresses()




                SelectListviewRow(Me.lvwPeopleList, GlobalCRM.CurrentCandidateID)
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "tabCompany_GotFocus")
        End Try
    End Sub

    Private Sub tabCase_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles tabCase.GotFocus

    End Sub

    Public Sub tabCase_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles tabCase.Loaded
        Dim myData As System.Data.DataTable = Nothing
        Dim myCases As System.Data.DataTable = Nothing

        Dim myRow As DataRow = Nothing
        Dim myNewRow As DataRow = Nothing
        Dim CaseList As System.Data.DataTable
        Try

            If loadTabCases = False Then

                loadTabCases = True
                m_strCurrencyChar = CRM.BusinessLayer.CommonDataFunctions.GetCurrencyCodeCharacter(GlobalCRM.CurrentCaseID)
                'Me.RemoveHandlers()

                If GlobalCRM.CurrentCompanyID > 0 Then


                    If radCaseAll.IsChecked = True Then
                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllCases, CaseTypes.Company))
                    ElseIf radCaseClosed.IsChecked = True Then
                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.Closed, CaseTypes.Company))
                    ElseIf radCaseInit.IsChecked = True Then
                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.Initiated, CaseTypes.Company))
                    ElseIf radCasePreSale.IsChecked = True Then

                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.PreSale, CaseTypes.Company))
                    ElseIf radCaseOpen.IsChecked = True Then
                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllOpen, CaseTypes.Company))
                    End If
                    'myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllOpen, CaseTypes.Company))
                    If Not myData Is Nothing Then
                        If myData.Rows.Count > 0 Then
                            'Display open cases
                            grdCases.ItemsSource = myData

                            'Automatically selects first row, remove it.
                            Me.grdCases.SelectedItems.Clear()


                        Else
                            'No open cases, so display all cases
                            myData.Dispose()
                            'Me.grdCases.DataSource = DB.GetSQLDataTable(Me.CaseListSQL(ViewByStatus.AllCases, CaseTypes.Company))
                            Me.radCaseAll.IsChecked = True
                        End If
                    End If

                ElseIf GlobalCRM.CurrentCandidateID > 0 Then

                    ' Dim myData As DataTable
                    If radCaseAll.IsChecked = True Then
                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllCases, CaseTypes.Candidate))
                    ElseIf radCaseClosed.IsChecked = True Then
                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.Closed, CaseTypes.Candidate))
                    ElseIf radCaseInit.IsChecked = True Then
                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.Initiated, CaseTypes.Candidate))
                    ElseIf radCasePreSale.IsChecked = True Then

                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.PreSale, CaseTypes.Candidate))
                    ElseIf radCaseOpen.IsChecked = True Then
                        myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllOpen, CaseTypes.Candidate))
                    End If
                    If Not myData Is Nothing Then
                        'myData = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllOpen, CaseTypes.Candidate))
                        If myData.Rows.Count > 0 Then
                            'Display open cases
                            ' DataBinding.BindListView(myData, Me.grdCases)
                            Me.grdCases.ItemsSource = myData

                        Else
                            'No open cases, so display all
                            myData.Dispose()

                            'MG 17/08/07 This was commented out???
                            Me.grdCases.ItemsSource = CommonDataFunctions.GetSQLDatatable(Me.CaseListSQL(ViewByStatus.AllCases, CaseTypes.Candidate))
                            Me.radCaseAll.IsChecked = True
                        End If
                    End If

                End If

                If GlobalCRM.CurrentCaseID = 0 And GlobalCRM.CurrentCompanyID = 0 Then
                    If Not IsNothing(Me.grdCases.DataContext) Then
                        'If CType(Me.grdCases.DataSource, DataTable).Rows.Count > 0 Then
                        Dim currentRow As DataRowView = CType(grdCases.Items(0), DataRowView)
                        GlobalCRM.CurrentCaseID = currentRow("caseid")
                        'End If
                    End If
                Else
                    'Remembered case id from history screen
                End If

                myCases = Me.grdCases.ItemsSource()
                CaseList = New System.Data.DataTable
                With CaseList.Columns
                    .Add(New DataColumn("casename", System.Type.GetType("System.String")))
                    .Add(New DataColumn("caseid", System.Type.GetType("System.Int32")))
                End With

                If Not IsNothing(myCases) Then

                    ' i don't know what this bit is doing, but it didn't like the fact I had changed the column names for the grdCases datagrid (in the sql)
                    For Each myRow In myCases.Rows
                        myNewRow = CaseList.NewRow
                        myNewRow.Item("caseid") = myRow.Item("CaseID")
                        myNewRow.Item("casename") = myRow.Item("CaseID") & " / " & myRow.Item("Product") & " / " & myRow.Item("Status")
                        CaseList.Rows.Add(myNewRow)
                    Next


                End If
                Me.SelectedCase_Active()
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "tabCase_GotFocus")
        Finally
            myData = Nothing
            myCases = Nothing
            CaseList = Nothing
            myData = Nothing
            myNewRow = Nothing
        End Try
    End Sub


    Private Sub MFB5_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MFB5.Click
        Me.MFB_Execute(CType(sender, Button).Tag)
    End Sub

    Private Sub tabEvent_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles tabEvent.Loaded

    End Sub

    Private Sub grdCases_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs) Handles grdCases.SelectionChanged

    End Sub
End Class

